• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is it possible to get variable value using a string containing variable name?

 
Kian Peng Yong
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear sir,

I have a variable name = home.canvas.color.

String home.canvas.color = "purple";

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?

If so, can you show me please?

Thank you very much.

Best regards,
Yong

 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Prasad Krishnegowda
Ranch Hand
Posts: 670
4
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abimaran Kugathasan wrote:
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..
 
subodh k kumar
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have valid variable name then by using refelection API(java.lang.reflect.Field)you can retrieve the expected value.
 
Ash Kondhalkar
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1337
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ugh. Why would you want to use reflection? If you need variables of which you do not know the names beforehand, use a Map:
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prasad Krishnegowda wrote:
No, its not legal..

That's why, I've asked!
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Kian Peng Yong
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic