Umar Iqbal
Umar Iqbal

Reputation: 689

Naming an object dynamically?

My problem is to name an object dynamically when it is created and the name comes as input from user.

The following is my code in which I can create an object dynamically but I have to name it specifically before like in this case 'obj'

private Class ClassName=null;
private Object obj=null;

ClassName=Class.forName(token[2]);
obj=ClassName.newInstance();

all I need is to create object as the user specifies its name like if he says object must be named 'x' rather than 'obj'

Upvotes: 0

Views: 84

Answers (2)

JB Nizet
JB Nizet

Reputation: 692231

Objects don't have names. Variables have. But you can't create variables dynamically. If you want to associate objects with names, use a Map<String, Object>:

Map<String, Object> objectsByName = new HashMap<String, Object>();
...
objectsByName.put("Joe", obj);
...
Object objectNamedJoe = objectsByName.get("Joe");

Upvotes: 5

Arsen Alexanyan
Arsen Alexanyan

Reputation: 3141

You can't rename your variable name cause this is a compile time process, user inputs are runtime

Upvotes: 3

Related Questions