-2

I want to covert the value of a String to a variable name in Java.

I've found the solution for this problem, but in javascript(Convert string to variable name in Javascript) not in java.

boolean hi;
boolean bye;
boolean question;

String myString = "hi";

public void changeBooleanValue(){

    [value of myString]= true;
}

Can you help me please?

Community
  • 1
  • 1
Punpuf
  • 2,042
  • 1
  • 19
  • 30
  • 1
    Here are two helpful posts I found: [Creating a variable name using a String value](http://stackoverflow.com/questions/8631935/creating-a-variable-name-using-a-string-value) & [To use a string value as a variable name](http://stackoverflow.com/questions/20974558/to-use-a-string-value-as-a-variable-name) – CubeJockey Dec 29 '15 at 19:30
  • This sounds like an [XYProblem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you actually trying to do? There's probably a much better way to do it in Java than what you're trying to do. – azurefrog Dec 29 '15 at 19:38

1 Answers1

2

This should work:

boolean hi;
boolean bye;

void setTrue(String name) {
    try {
        this.getClass().getField(name).set(this,Boolean.TRUE);
    } catch (Throwable e) { }

}

This is not common way to do things, but sometimes it is necessary to do it this way.

Rediska
  • 1,392
  • 10
  • 14