If I obtain an input from user = "home.canvas.color", is there a way that I can retrieve the value "purple" from the actual variable home.canvas.color?
Kian Peng Yong wrote:
I have a variable name = home.canvas.color.
String home.canvas.color = "purple";
Is this a legal variable name in Java?
No, its not legal..
Regards, Prasad
SCJP 5 (93%)
subodh k kumar
Greenhorn
Joined: Aug 19, 2009
Posts: 16
posted
0
If you have valid variable name then by using refelection API(java.lang.reflect.Field)you can retrieve the expected value.
SCJP1.4 , SCWCD 5
Ash Kondhalkar
Ranch Hand
Joined: Jun 14, 2006
Posts: 43
posted
0
Hi,
Try this code.
The variable in your case "home.canvas.color" as to be defined as instance variable in a class. Also since java naming convention doesnt allow "." in its name you need to give some different name. Then you can follow above code to get what you are trying.
Thanks
Ashwin
Lester Burnham
Rancher
Joined: Oct 14, 2008
Posts: 1337
posted
0
Ugh. Why would you want to use reflection? If you need variables of which you do not know the names beforehand, use a Map:
Ash, please UseCodeTags next time. I've replaced your asterisk lines with code tags, and not only does it not mess up the forum layout, it also preserves indentation and adds syntax highlighting.