brumhee
brumhee

Reputation: 13

Create an instance of a class referenced by a variable generated in a method

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

Upvotes: 1

Views: 2861

Answers (2)

Jeroen Rosenberg
Jeroen Rosenberg

Reputation: 4682

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

Upvotes: 0

Jon Freedman
Jon Freedman

Reputation: 9697

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

Upvotes: 1

Related Questions