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
精彩评论