2016-07-04 71 views
0

我有一個字符串數組這樣,我們可以將String值作爲變量參考嗎? (變量名)

String[] components = {"jButton1,jLabel1,jTextField1"}; 

我想用這樣這個變量的字符串名稱,

components[0].setText("Some Text"); 

我可以使用字符串值作爲一個變量名?這個所有變量聲明都在我的代碼中。

+2

爲什麼要編寫'components [0] .setText()'而不是'jButton1.setText()'? – Kayaman

+2

你可以通過反思。但爲什麼不只是將實際引用存儲在數組中? –

+2

或者一張地圖。 'map.put('jButton1',jButton1)',然後'map.get(buttonName).setText(「Some text」)''。 – bezmax

回答

0

雖然你並不需要改變變量名,同時要爲國際化,爲了得到一個變量名,你可以試試這個:

Class<?> myClass = this.getClass(); 
Field field = myClass.getField("fieldName"); 

if(field instanceof JButton) 
    ((JButton)field).setText("My text"); 

看看這個教程,可以幫助 http://omtlab.com/java-reflection-tutorial/

+0

不同意反射,有(例如)get/putClientProperty – mKorbel

相關問題