• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamically generated objects

 
Jon Wilbanks
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Val Dra
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Val Dra
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Val Dra
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i will post the code on monday sorry i can't find it at home.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jon Wilbanks
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic