反射之------获得运行时类的指定构造方法以及创建对象的操作

package com.heima.userJSTL;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class GetConstrect {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //获取当前运行时类的指定构造器,并创建该构造器的对象(这种方法并不常用我们一般的使用的是直接通过
        // 当前运行时类的静态方法newInstance();直接创建一个对象,(底层还是使用的空参构造))
        Class<Person> aClass = Person.class;
        Constructor<Person> declaredConstructor = aClass.getDeclaredConstructor(String.class);//构造方法不需要区分方法名,参数只需要形参列表
       //暴力反射设置该构造器可以被访问
        declaredConstructor.setAccessible(true);
        Person person = declaredConstructor.newInstance("张三");
        System.out.println(person);

        //但是我们常用的穿件对象的方法是直接使用当前运行时类的Class对象的.newInstance();方法进行创建对象
        Person person1 = aClass.newInstance();
        System.out.println(person1);
        //使用当前运行时类的Class对象的.newInstance();方法的前提是:
        //1.必须要有空参构造器
        //2.空参构造的权限修饰符要够,一般是public

    }
}
迎风少年
原文地址:https://www.cnblogs.com/ZYH-coder0927/p/13784580.html