Create new object from a string in Java:
refer to:lautturi.comString 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