This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
How can I create multiple objects of a class without knowing the number of objects I will need to create? For example; I have a Name class, the names I need to create the objects are in a file, how can I read each line of the file and create an instance of the Name class for each line?
well the best way you can do in this case is to use reflection. You can also dynamically load classes using Class.forName("someCLass") which someClass is your class when you will go though the file reading it line by line and just pass a string to forClass which will load the class into memory. Also take a look at the java.lang.refl package. You will find what you need. If you need some farther help i can send you a program as an example i made or just look at the sun.com they have tutorials section which descibes how to use reflection.
Since you know that the objects are going to be of the Name class, you don't really need reflection. You could just put the instantiation in a while loop and keep reading the names and creating the instances while not end of file.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Joined: Jan 26, 2001
Not really , let's say he has just strings in a text file something like this Button Label myObject let's say that he needs to construct an object of this types and then call methods on them in his program how would he achieve this without reflection ? I'll post a simple example where i just did that and it worked out fine.
Joined: Jan 26, 2001
i will post the code on monday sorry i can't find it at home.
Joined: Sep 29, 2000
I guess this depends on how you read this question. It looks to me like he is asking to create alot of Name objects with different internal values like "Cindy" and "Val" etc. only he just doesn't know how MANY names are in the file.
Joined: May 11, 2001
Thanks to everybody for the help. It's really nice to find a place with so many helpful folks. BTW I found a solution for my problem. An array of objects does nicely: Name  theNames = new Name[cnt]; Thanks again.