创建同一类的多个对象的问题

时间:2014-05-14 23:04:21

标签: java eclipse class object

我正在尝试创建同一个类的多个对象,但我希望从某个文件中获取对象名称(变量名称)。我怎么能这样做?

例如:

Example one = new Example();

我想对多个对象做同样的事情,但我需要它们命名为onetwothreefour,...(不知道具体数字)对象和我不能简单地复制粘贴它并将one更改为two,因为我正在从文件中读取它们)。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

你需要为你的名字设一个“字典”文件(包含1:one,2:2,......)

然后你必须解析该文件并创建一个java文件:

public String createFileContent( List<String> variableNames ) {
  StringBuffer buffer = new StringBuffer();
  for( String name : variableNames ) {
    buffer.append( "Example " ); 
    buffer.append( name ); 
    buffer.append( " = new Example();" ); 
    buffer.append("\n");
  }
  return buffer.toString();
}

对于更高级的代码生成,您可以考虑使用类似的专业技术 https://developers.google.com/closure/templates/ http://www.stringtemplate.org/ 或更通用的解决方案: http://java-source.net/open-source/template-engines