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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie question regarding variable name substitution

Status
Not open for further replies.

zombieZero

Technical User
Apr 7, 2004
28
0
0
US
I'm new to the Java world, and previously worked with Tcl...in TCL, there is a command called 'subst' which basically allowed for this:

proc setInfo {param val} {

set $param $val
return "Param $param was set to [subst $$param]"

}

setInfo name Bob
Param name was set to Bob.

Basically, I pass the method the name of the variable I want to change, along with the value to change it to. The method then sets the variable internally.

...I want to do the same thing in Java, and I have a feeling the answer is in front of my face but I'm not seeing it. Can anyone steer me in the right direction?

Thanks!

 
Thanks - that definitely helps...I fiddled with it a long time and came up with this to kind of act as my 'subst':

import java.lang.reflect.*;

public void setVar(testObj obj, String name, int val) throws Exception {

Field field = obj.getClass().getDeclaredField(name);
field.setInt(obj, val);

}

...it works for integers, but I'd like to make it work for all types (at least String in addition to int)...if I can't manage it I can just have a 'setInt' and 'setString' but I think there must be a way to pull the type from out of 'field'.

Does this solution seem reasonable? I'm still getting my footing and don't want to develop bad habits...
 
Maybe you should consider the way of doing things. You're talking about passing variables by reference and Java doesn't work that way.

You can set the value outside the method or wrap it in an object with set and get methods but I'd really encourage you to not use reflection as it's expensive and hard to maintain

Cheers,
Dian
 
instead of
Code:
setInfo name Bob
you just write
Code:
name = "Bob"

Why do you want to use the complicated way? Yes, I know, there are rare cases where you need a generic way, but that's not fun. You may work with (Object, Object) and a Map, but you should avoid it if possible.

It circumvents the type system with its security, so maybe you should find an oop-solution for your problem. Which we don't know, so we can't suggest something more concrete.

don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top