Question

I am trying to create multiple objects of the same class but I want the object names (the variable names) to be taken from a certain file. How can I do this?

For example:

Example one = new Example();

I want to do the same for multiple objects but i need them named one, two, three, four, ... (without knowing the exact number of objects and I can't simply just copy paste it and change one to two as I am reading them from a file). Is there a way to do this?

Was it helpful?

Solution

You need to have a "dictionary" file for your names (that will contain 1:one, 2:two, ...)

Then you'll have to parse that file and create a java file :

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();
}

For more advanced code generation, you might consider using specialized technologies like https://developers.google.com/closure/templates/ http://www.stringtemplate.org/ or more generic solutions : http://java-source.net/open-source/template-engines

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top