开发者

Using the value of a variable instead of its name for new variable declaration

Su开发者_如何学Pythonppose I've a variable in java

String test=new String();  

Now i want to declare a new variable with its name equal to the value of the variable 'test'.


You can't do that in Java, use a java.util.Map instead.

For example:

Map<String, Object> map = new HashMap<String, Object>();
map.put("key1", "key2");
map.put((String) map.get("key1"), "whatever");


That is not possible, because the name is fix to compile time!


as far as I know, Java doesn't allow adding variables in reflection however, you can use Map<String,Object> to achieve it.

String test = new String();
Map<String,Object> map = new HashMap<String, Object>();
Object myNewObject = new Object();
map.put(test,myNewObject);

now, you seek your new objects by:

map.get(test);

amit

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜