I want the user to enter the name of the object to be used in the code. For example, if I have a class
public class Person{
.......
}
now instead of me creating an object with a specific name like
Person student;
I want the user to enter the name for the object maybe like teacher, and then an object teacher of the class person will be created. I do not know if this is even possible in java, many of the solutions I looked up were using a map, but the explanations were not clear enough for me as I am new to java.
So, if anyone could explain how it can be done with code snippets it would be wonderful.
Also please explain how hashmaps work in java and if they can be used to implement the problem above. I would be really grateful if explained with code examples
It's not possible. Names of local variables are not even persistent in the compiled Class file. Names of fields are there, as it is the part of API, but you would have to modify the Class file runtime - and that is not what do you want.
With Hashtable, it may be done like this:
Then you may get your "variable" by:
When I guess what you are trying to do, this is some more helpful example: