Antrromet
Antrromet

Reputation: 15414

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

Suppose 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'.

Upvotes: 1

Views: 1096

Answers (3)

amit
amit

Reputation: 178411

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

Upvotes: 2

Bence Olah
Bence Olah

Reputation: 684

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");

Upvotes: 4

Tim
Tim

Reputation: 2831

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

Upvotes: 2

Related Questions