有参构造器的类:
public class Demo { private String a; private Integer b; public Demo(String a) { this.a = a; } public Demo(Integer b) { this.b = b; } public String getA() { return a; } public Integer getB(){ return b; } }
无参构造器的类:
public class Demo2 { public String getString(String s){ return s; } }
测试类:
public class Test { public static void main(String[] args) throws Exception { //反射,用指定的构造器新建一个对象 Class c = Demo.class; Constructor<Demo> constructor = c.getConstructor(String.class);//通过构造器参数类型查找构造器 Demo demo = constructor.newInstance("aa"); System.out.println(demo.getA()); Constructor<Demo> constructor1 = c.getConstructor(Integer.class);//通过构造器参数类型查找构造器
Demo demo1 = constructor1.newInstance(2); System.out.println(demo1.getB()); //反射,用默认构造器创建对象 Class c2 = Demo2.class; Demo2 demo2 = (Demo2) c2.newInstance(); System.out.println(demo2.getString("dddd")); } }
输出:
aa
2
dddd