2

How do i create a new instance of an object from a string?

I want to do this:

Event event = new Event("hello");  
event.setName("nice!");

but only having

String object = "Event";  
String object_variable_name = "event";  
String object_params = "hello";

Is this possible?

3

3 Answers 3

2

You can instantiate a class with the reflection API. But you need the full class name, the simple name (= with no constructor) is not enough.

Class clazz = Class.forName("com.example.Event");
Constructor constructor = clazz.getConstructor(String.class);
Object instance = constructor.newInstance("hello");

Assigning it to a variable where the variables name and type are stored in Strings is not possible. The usual pattern to implement this is to use a map:

Map<String, Object> events = new HashMap<String, Object>();
events.put("event", event);
Sign up to request clarification or add additional context in comments.

1 Comment

This looks good, but this line "Event event = (Event) constructor.newInstance("hello");" assumes that I know the type is Event, but I only have the string value
0

You can use java.lang.Class's getConstructor isnstead.

Comments

0

Here is how you get the class instance (so you can call the constructor): How to get a Class Object from the Class Name in Java

Now you can you the Beans API to get the getter for the property name. See this question: Java Reflection: Instantiate a new object with specified type

Or you can use reflectasm or reflections or commons-beanutils to make your life much more simple

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.