1

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

2
  • newClassName is a string. You cannot use as later as 'LightningStorms`. Anyway - your question is not clear to me. Commented Sep 6, 2010 at 8:36
  • what is the type and value of 'SS' ? Commented Sep 6, 2010 at 8:52

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Or Class.newInstance() if the class has an zero-arg constructor
so would I put the new name in the brackets as in Class.newInstance(newClassName) or Class.forName(newClassName)?
Class.forName(newClassName).newInstance()
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.