通过反射获取构造方法对象

package MyreflectDemo2;

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

public class ReflectDemo2 {
    public ReflectDemo2() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //method1();  有参构造

       // method2();//无参构造方法
        //method3();//无参构造方法(过时方法)
        method4();//创建私有化带参方法
    }

    private static void method4() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //1.获取对象
        Class aClass = Class.forName("MyreflectDemo2.Student");
        //2.获取一个私有化的构造方法
        Constructor constructor = aClass.getDeclaredConstructor(String.class);//能看到私有化的方法不能用
        //被private修饰的成员,不能直接使用,如果反射强行获取使用,需要临时取消检查
        constructor.setAccessible(true);//强行使用
        //直接创建对象
        Student student = (Student) constructor.newInstance("李世康");
        System.out.println(student);
    }

    private static void method3() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class aClass = Class.forName("MyreflectDemo2.Student");
        //在Class类中,有一个newInstance方法,可以利用空参直接创建一个对象
        Student student = (Student) aClass.newInstance();
        System.out.println(student);
    }

    private static void method2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class clazz = Class.forName("MyreflectDemo2.Student");

        //2.获取构造方法对象
        Constructor constructor = clazz.getConstructor();
        //3.利用newInstance创建Student的对象
        Student student = (Student) constructor.newInstance();
        System.out.println(student);
    }


    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //T newInstance(Object...initargs);根据指定的构造方法创建对象
        //1.获取class对象
        Class clazz = Class.forName("MyreflectDemo2.Student");

        //2.获取构造方法对象
        Constructor constructor = clazz.getConstructor(String.class, int.class);
        //3.利用newInstance创建Student的对象
        Student student = (Student) constructor.newInstance("zhangsan", 23);
        System.out.println(student);
    }

}
反射获取私有化构造方法时 Constructor constructor = aClass.getDeclaredConstructor(String.class);//能看到私有化的方法不能用,所以需要JVM取消临时检查   
constructor.setAccessible(true);//强行使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值