1

I am attempting to run a method that takes in an string and creates the object using the string as the object's variable:

public void createObj(String objName){
    Obj objName = new Obj();
}

Is this even possible? If so, how may I accomplish it?

1
  • What? Why would you want to do this? Commented Mar 24, 2013 at 15:55

4 Answers 4

0

You cannot use an expression to name a variable in Java. The closest you can get, I think, is to populate a Map<String, Obj> that can be used to look up Obj instances by name.

public void createObj(String objName, Map<String, Obj> symbolTable){
    symbolTable.put(objName, new Obj());
}
Sign up to request clarification or add additional context in comments.

Comments

0

In a nutshell, no, this cannot be done. You can't create a named local variable at runtime.

If you want to associate names with objects, you could use a Map<String,Object>.

Comments

0

No you can't do it for a simple reason. You cannot have 2 local variables with a same name because the compiler cannot differentiate.

Comments

0

No its not possible. Declare all the local variable with different name.

A class and its members are defined and then compiled to byte code, so thse cannot be modified at dynamic at run-time.

public void createObj(String objName){
    Obj objectName = new Obj();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.