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?

4 Answers4

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());
}
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
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();
}
Ajay S
  • 48,003
  • 27
  • 91
  • 111
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>.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
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.

mani_nz
  • 4,522
  • 3
  • 28
  • 37