Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic Class Selection

Status
Not open for further replies.

fatcodeguy

Programmer
Feb 25, 2002
281
CA
Hi,

I'm wondering if this is at all possible. Based on an input, a String named after a Class, I want to instantiate an object as that class. All objects are subclasses of an abstract class I defined, which extends Threads.
So now I do the following

Code:
Thread myThread = null;
if (input==myThread1Name)
  myThread = new MyThread1();
else if (input==myThread2Name)
  myThread = new MyThread2();
... 
...

and so on. The problem with this is that if I want to add new implementations, I have to modify the classes that call this type of code, instead of changing a config file that has the classname I want to use.

I'd like to see something like this
Code:
  myThread = SomeJavaFunction(inputclassname);

I'm hoping that java has something like this. Doe this make sense? Is this at all possible, or am I just being stupid?

All help greatly appreciated!! Thanks!!
 
You want to look at the reflection API :
Bear in mind though, this API is expensive to use in terms of runtime, and should be used as sparingly as possible. Having said that, we use it in our production system for precisely the reason you stated :)

--------------------------------------------------
Free Database Connection Pooling Software
 
Thanks!

For a minute there I thought I was talking crazy
 
I do something similar in a very simple minded way (and, therefore, no doubt very inelegantly). In my case, I wanted to launch java app's on a PDA without having to install each of them with it's own icon and start script. Instead of an input string I have a text file which consists only of class names. Each class has a constructor that does what's necessary to run the app.

I read the text file:
BufferedReader iniFile = new BufferedReader(new FileReader("zlnch.txt"));
and put the results in a Choice object:
while ((rs =iniFile.readLine()) != null) {apln.add(rs);}
When a class is chosen, I instantiate it:
String ct = apln.getSelectedItem();
try {
Class cls = Class.forName(ct);
cls.newInstance();
}


I imagine something of the sort would work for you if "ct" was an input string

Bob Rashkin
rrashkin@csc.com
 
Yes, but without reflection, how can you do anything useful ? All you are doing is instantiating a class ...

--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top