反射构造方法,用构造方法实例化对象:
测试代码:
package reflect;
import java.lang.reflect.Constructor;
public class Test15 {
public static void main(String[] args) throws Exception {
// 不使用反射机制创建对象
Student15 s1 = new Student15();
Student15 s2 = new Student15(1001, "张三", "2020-7-27", true);
System.out.println(s1); // Student15{no=0, name='null', birth='null', sex=false}
System.out.println(s2); // Student15{no=1001, name='张三', birth='2020-7-27', sex=true}
// 使用反射机制创建对象
// 反射获取一个类
Class theClass = Class.forName("reflect.Student15");
// 获取无参数构造方法
Constructor c1 = theClass.getDeclaredConstructor();
// 获取有参数构造方法
Constructor c2 = theClass.getDeclaredConstructor(int.class, String.class, String.class, boolean.class);
// 无参数构造方法实例化对象
Object obj1 = theClass.newInstance();
Object obj2 = c1.newInstance();
System.out.println(obj1); // Student15{no=0, name='null', birth='null', sex=false}
System.out.println(obj2); // Student15{no=0, name='null', birth='null', sex=false}
// 有参数构造方法实例化对象
Object obj3 = c2.newInstance(1002, "李四", "2020-7-27", false);
System.out.println(obj3); // Student15{no=1002, name='李四', birth='2020-7-27', sex=false}
}
}
class Student15 {
int no;
String name;
String birth;
boolean sex;
public Student15() {
}
public Student15(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 "Student15{" + "no=" + no + ", name='" + name + '\'' +
", birth='" + birth + '\'' + ", sex=" + sex + '}';
}
}