一、Contructor类
Constructor是构造方法类,类中的每一个构造方法都是Constructor的对象,通过Constructor对象可以实例化对象
1、Class类中与Constructor相关的方法
1. Constructor getConstructor(Class... parameterTypes)
根据参数类型获取构造方法对象,只能获得public修饰的构造方法。
如果不存在对应的构造方法,则会抛出 java.lang.NoSuchMethodException 异常。
2. Constructor getDeclaredConstructor(Class... parameterTypes)
根据参数类型获取构造方法对象,包括private修饰的构造方法。
如果不存在对应的构造方法,则会抛出 java.lang.NoSuchMethodException 异常。
3. Constructor[] getConstructors()
获取所有的public修饰的构造方法
4. Constructor[] getDeclaredConstructors()
获取所有构造方法,包括privat修饰的
2、Constructor类中常用的方法
1. T newInstance(Object... initargs)
根据指定参数创建对象。
2. void setAccessible(true)
暴力反射,设置为可以直接访问私有类型的构造方法
3、示例代码
学生类(被测试类)
public class Student {
// 姓名
private String name;
// 性别
public String gender;
// 年龄
private int age;
// public 有参构造方法
public Student(String name, String gender, int age) {
System.out.println("public 修饰有参数构造方法");
this.name = name;
this.gender = gender;
this.age = age;
}
// public 无参构造方法
public Student() {
System.ou