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?
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.
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
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.