2015-12-29 44 views
-3

我想要將一個String的值轉換爲Java中的變量名。如何將字符串轉換爲Java中的變量名?

我發現這個問題的解決方案,但在JavaScript(Convert string to variable name in Javascript)不在java中。

boolean hi; 
boolean bye; 
boolean question; 

String myString = "hi"; 

public void changeBooleanValue(){ 

    [value of myString]= true; 
} 

你能幫助我嗎?

+1

這裏有兩個有用的文章,我發現:[使用字符串值創建一個變量名稱](http://stackoverflow.com/questions/8631935/creating-a-variable-name-using-a-string-value) &[使用字符串值作爲變量名稱](http://stackoverflow.com/questions/20974558/to-use-a-string-value-as-a-variable-name) – CubeJockey

+0

這聽起來像一個[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。你究竟在做什麼?在Java中執行它的方式可能比你想要做的要好得多。 – azurefrog

回答

1

這應該工作:

boolean hi; 
boolean bye; 

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

} 

這不是做事情常用的方法,但有時有必要做這種方式。