时间:2021-10-03 17:01:46 | 栏目:JavaScript代码 | 点击:次
如下所示:
/** * Created by hunt on 2017/6/27. * 测试的实体类 * @Data 编译后会自动生成set、get、无惨构造、equals、canEqual、hashCode、toString方法 */ @Data public class Person { private String name; private int age; public Person(String name){ this.name = name; } public Person(int age){ this.age = age; } public Person(String name,int age){...} }
import java.lang.reflect.Constructor; /** * Created by hunt on 2017/6/27. */ public class NewInstanceTest { public static void main(String[] args) { Class<Person> personClass = Person.class; try { Constructor<?> constructor = personClass.getConstructor(java.lang.String.class); Person p = (Person) constructor.newInstance("hunt"); System.out.println(p); } catch (Exception e) { e.printStackTrace(); } } }
总结:通过class.getConstructor(parameterTypes)获得对应的构造器,然后通过constructor.newInstance(parameterTypes)实例化对象。