1

How would one create a new object in Java using a variable name provided by the user?

For example: if a user enters the string Hello as the name, I'd like to create a variable like so: Object Hello = new Object();

Thanks

Priidu Neemre
  • 2,813
  • 2
  • 39
  • 40
Xellic
  • 25
  • 3

2 Answers2

4

Use a Map<String, Object> where you use the user input (in this case, "Hello") as the key and the desired object as value.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

What you are trying to do is dynamically create variables at runtime. This unfortunately is not possible to do in java.

There are alternative ways to go about this. More info here: Is it possible to create variables at runtime in Java?

Community
  • 1
  • 1
l-l
  • 3,804
  • 6
  • 36
  • 42