Jump to content


Dynamic Instance Naming


  • Please log in to reply
2 replies to this topic

#1 M@rk

M@rk

    Newbie

  • Members
  • Pip
  • 2 posts

Posted 17 September 2005 - 02:21 AM

I am an experienced programmer (VB, Lisp, OOP, etc.) but am new to Java.  Is it possible to assign object names dynamically at run-time?  This is possible in Lisp and can be very handy.

For instance, I might want to generate a string and then use that string as the name of an instance of a class, rather than hard-coding all object names.  Sort of type-casting a string to an object reference.

Any other technique that accomplishes the same objective would be great.

Thanks for any help, M@rk

#2 Phil^

Phil^

    Advanced Member

  • Members
  • PipPipPip
  • 175 posts

Posted 17 September 2005 - 10:19 AM

QUOTE(M@rk @ Sep 17 2005, 02:21 AM)
I am an experienced programmer (VB, Lisp, OOP, etc.) but am new to Java.  Is it possible to assign object names dynamically at run-time?  This is possible in Lisp and can be very handy.

For instance, I might want to generate a string and then use that string as the name of an instance of a class, rather than hard-coding all object names.  Sort of type-casting a string to an object reference.

Any other technique that accomplishes the same objective would be great.

Thanks for any help, M@rk

View Post



I dont think you can do it the way you describe, but one way you could get around it is to use a hashmap
Store all the objects in a hashmap, with a corresponding string for a key. that string can be the name you generate if you wish

basically, in jdk1.5 :
import java.util.*;

Hashmap db = new Hashmap<String,CLASS_TYPE>;
...
CLASS_TYPE temp = new CLASS_TYPE()
db.put("name",temp); // stores an object in hashmap
temp = null; // nuke temp
...
CLASS_TYPE retrieved = db.get("name"); // retrieves the object keyed by "name"

#3 M@rk

M@rk

    Newbie

  • Members
  • Pip
  • 2 posts

Posted 20 September 2005 - 03:52 AM

Phil^ - thanks for pointing me in the right direction.  Actually, for my app I don't need to reference the object by name, but wanted to create objects that I could iterate over.  An ArrayList, or even an array works fine.

CODE

// Declare and allocate an array of CLASS_TYPE instances
CLASS_TYPE arrayVar[] = new CLASS_TYPE[3];

// Populate array with objects
arrayVar[0] = new CLASS_TYPE(<arg-list>);
arrayVar[1] = new CLASS_TYPE(<arg-list>);
arrayVar[2] = new CLASS_TYPE(<arg-list>);

// Iterate through CLASS_TYPE objects
for CLASS_TYPE aV : arrayVar) {
 // iterated code - aV is an instance of CLASS_TYPE from the array
}


Thanks again!
M@rk