how to create new object from a string in Java

how to create new object from a string in Java

Create new object from a string in Java:

refe‮r‬ to:lautturi.com
String className = "Class1";
Object obj = Class.forName(className).newInstance();

Create new object from class with parametrized constructor :

/**
 * @author lautturi.com
 * Java example: java create class object from string 
 */
package hello;

import java.util.*;
import java.lang.reflect.*;

class Stuff {
	public Stuff(Integer id, String str) {
		_id = (int) id;
		_name = str;
	}

	int _id;
	public String _name;

	public String toString() {
		return this._name;
	}
}

public class Lautturi {

	public static void main(String[] args) throws Exception {
		String className = "hello.Stuff";
		
		Integer id = 123;
		String name = "lautturi";
		Class cl = Class.forName(className);
		Constructor con = cl.getConstructor(Integer.class, String.class);
		@SuppressWarnings("deprecation")
		Object o = con.newInstance(id, name);
		System.out.println(o.toString());
	}
}

output:

lautturi
Created Time:2017-09-20 00:05:33  Author:lautturi