如何使用字符串的值作为变量名称

问题描述:

我的问题是假设有一个字符串变量,如String abc="Shini";如何使用字符串的值作为变量名称

所以有可能通过一些自动的方式使用"Shini"作为新的变量名称而不是通过明确的键入。

String abc = "Shini"; 
String Shini = "somevale"; 
+5

不,这是不可能的。 – Joydeep

+0

你是什么意思的自动手段? –

+0

是的。您可以使用。 http://stackoverflow.com/questions/276555/setting-variables-by-name-in-java –

变量必须在编译时声明,所以没有它不是不可能性在运行时,它在我脑海中 最好的办法是把它作为一个地图键

String abc = "Shini"; 
Map<String, String> myMap = new Hashmap<>(); 
myMap.put(abc, "something"); 

然后myMap.get (“Shini”)会给“东西”。

是的。您可以使用。

class Foo { 
    private int lorem; 
    private int ipsum; 

    public Foo(){} 

    public setAttribute(String attr, int val) throws NoSuchFieldException, IllegalAccessException { 
     Field field = getClass().getDeclaredField(attr); 
     field.setInt(this, val); 
    } 

    public static void main(String [] args) { 
     Foo f = new Foo(); 
     f.setAttribute("lorem", 1); 
     f.setAttribute("ipsum", 2); 
    } 
} 

我没有编译这段代码。请检查这是否可以有轻微的错误。