Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

object from Stringname???

 
Ner min
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

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";
aRef=s.findInstanceWithThisNameAndMakeRefToIt();
or anything like this?
 
Henry Wong
author
Marshal
Pie
Posts: 21112
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java has the reflection API, which allows you to at runtime instantiate the classes that you want and the determine methods to call.

Henry
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic