反射reflect——使用获取到的构造器创建对象

本文通过三个不同的方法展示了如何使用Java反射机制来创建不同类型的对象。包括:创建公共无参构造对象;通过获取公共有参构造方法创建对象;以及获取私有构造方法并创建对象的过程。

Student类需要去上一篇文章中查看

代码实现

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

public class myfl2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//        method1();
//        method2();
        method3();
    }

    private static void method3() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //获取一个私有的构造方法并创建对象
        //这里需要注意只能看到 如果要创建对象需要临时取消检查
        Class clazz = Class.forName("com.kerwin.myflect1.myflect.Student");
        //2.获取一个私有化的构造方法.
        Constructor constructor = clazz.getDeclaredConstructor(String.class);
        //被private修饰的成员,不能直接使用的
        //如果用反射强行获取并使用,需要临时取消访问检查
        constructor.setAccessible(true);
        //3.直接创建对象
        Student student = (Student) constructor.newInstance("zhangsan");
        System.out.println(student);
    }

    private static void method2() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        //简单创建公共无参构造对象
        Class clazz = Class.forName("com.kerwin.myflect1.myflect.Student");
        Student student = (Student) clazz.newInstance();
        System.out.println(student);
    }

    //这个是获取公共有参构造方法 创建对象
    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class clazz = Class.forName("com.kerwin.myflect1.myflect.Student");
        Constructor constructor = clazz.getConstructor(String.class,int.class);
        //创建对象
        Student student = (Student) constructor.newInstance("许仙",25);

        System.out.println(student);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值