File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes object from Stringname??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "object from Stringname???" Watch "object from Stringname???" New topic

object from Stringname???

Ner min
Ranch Hand

Joined: Sep 14, 2005
Posts: 76

if i have an object like:

and that SomeRefType has method doIt();
what i wont to do is get a string from user
(so user types "srt1" or "srt2" through TextFeld)
and call that objects method on behav of the passed String.
so if the user types "srt1" i wont to call srt1.doIt();

ok , i n�know i can do it with
if(string=="whatever") srt1.doIt()
if(string=="whatever2") srt2.doIt()

but i have many possibilities and dont wont to have that many if's

can java do anything like
String s="a";
or anything like this?
Henry Wong

Joined: Sep 28, 2004
Posts: 20538

Java has the reflection API, which allows you to at runtime instantiate the classes that you want and the determine methods to call.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Reflection will only work if srt1, srt2 are members, not locals-- and I wouldn't say it's the best way to do things.

Instead of using member variables (or in addition to them) use a HashMap. Store each object in a HashMap wusing the name you'll refer to it by as the key. Then take the user's string and call get(key) on the HashMap, and you'll get the object. You'll need to cast it to the correct type before calling its methods, of course.

[Jess in Action][AskingGoodQuestions]
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Ernest Friedman-Hill:
You'll need to cast it to the correct type before calling its methods, of course.

Unless you are using Java 5 generics.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
I agree with EFH. The user should not be required to know the names of the variables in your code. One way to avoid this is to use a HashMap as suggested above. If, like in your example, the names are differentiated by a number on the end, then perhaps an array or ArrayList would be a better Collection to use instead of a HashMap.


Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: object from Stringname???
It's not a secret anymore!