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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.