反射机制调用构造方法
Vip类
package com.happy.bean;
public class Vip {
int no;
String name;
String birth;
boolean sex;
public Vip() {
}
public Vip(int no) {
this.no = no;
}
public Vip(int no, String name) {
this.no = no;
this.name = name;
}
public Vip(int no, String name, String birth) {
this.no = no;
this.name = name;
this.birth = birth;
}
public Vip(int no, String name, String birth, boolean sex) {
this.no = no;
this.name = name;
this.birth = birth;
this.sex = sex;
}
@Override
public String toString() {
return "Vip{" +
"no=" + no +
", name='" + name + '\'' +
", birth='" + birth + '\'' +
", sex=" + sex +
'}';
}
}
反射测试类--ReflectTest12
package com.happy.reflection;
import com.happy.bean.Vip;
import java.lang.reflect.Constructor;
public class ReflectTest12 {
public static void main(String[] args) throws Exception {
//不使用反射机制创建对象
Vip v1 = new Vip();
Vip v2 = new Vip(110,"zhangsan","2001-10-11",true);
//使用反射机制创建对象
Class c = Class.forName("com.happy.bean.Vip");
//这种方式对象实例化会调用无参构造方法
Object obj = c.newInstance();
System.out.println(obj);
//调用有参构造
//第一步:先获取到这个有参数的构造方法
Constructor con = c.getDeclaredConstructor(int.class, String.class, String.class, boolean.class);//这里为4个参数的构造方法
//第二步:调用构造方法new对象
Object newObj = con.newInstance(110, "jackson", "1990-10-11", true);
System.out.println(newObj);
//获取无参构造方法
Constructor con2 = c.getDeclaredConstructor();
Object newObj2 = con2.newInstance();
System.out.println(newObj2);
}
}
运行结果:
从上面可以看到有2种调用无参构造方法的方式,一种是通过Class类实例调用,一种是反射获取构造方法,构造方法实例化调用。