tags:

views:

47

answers:

2

Ok so here is what I need to do:

I am reading in a CSV file and need to generate a new instance of a class for each line.

I then need to store the reference variable for the class in a List.

I am ok with most of this but how do I generate a class using a variable

something like this

string newClassName;
int a = 1; //counts number of loops

while (bufferedScanner.hasNextLine());
{
    newClassName = SS + a;

    LightningStorms newClassName = new LightningStorms();

    a = a + 1;

}

I have left out a lot of extra code but its the setting up of the new class that I am interested in.

I am current learning and this is part of an assignment so want to figure most out for myself (there is a lot more to the question than this) but am stuck so any guidance would be very welcome.

Many thanks

A: 

You can get an instance of a Class object for a particular name using Class.forName() - this needs to be a fully qualified class, so java.lang.String not String.

With the class object, you can construct a new instance using reflection, see Class.getConstructor()

Jon Freedman
Or `Class.newInstance()` if the class has an zero-arg constructor
Riduidel
so would I put the new name in the brackets as in Class.newInstance(newClassName) or Class.forName(newClassName)?
brumhee
Class.forName(newClassName).newInstance()
foret
A: 

How about:

SortedMap<String, LightningStorms> myMap = new TreeMap<String, LightningStorms>();
while (bufferedScanner.hasNextLine());
{
    String newClassName = SS + a; // or whatever you want
    myMap.put(newClassName, new LightningStorms());
}

At the end of the loop you have a map of LightningStorms objects for every line in your CSV file and every object is referenced by your "generated variable". You can access your object by using: myMap.get("referenceVariable") Additionally you can convert to a list and keep the order of the keys:

List<LightningStorms> myList = new ArrayList<LightningStorms>(myMap.values());

or you can have a List of reference names as well:

List<String> myReferences = new ArrayList<String>(myMap.keySet());
Jeroen Rosenberg