代码片段:通过反射对类进行实例化

本文详细介绍了如何使用Java反射机制来实例化一个类,并提供了具体的代码实现。文章首先检查传入的类是否为空或者接口,然后通过调用类的声明构造函数来进行实例化。此外,还展示了如何设置构造函数的可访问性以及处理实例化过程中可能出现的各种异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过反射对类进行实例化代码归结:

ABean a = BeanReflectUtils.instantiateBean(ABean.class);

a.setName("testName");

System.out.println(a.getName);

package com.demo.test.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

public class BeanReflectUtils {

    public static <T> T instantiateBean(Class<T> tClass) throws Exception {
        if (tClass == null) {
            throw new NullPointerException("Class must not be null.");
        }

        if (tClass.isInterface()) {
            throw new IllegalArgumentException("Class must not be interface.");
        }

        return instantiateBean(tClass.getDeclaredConstructor());
    }

    public static <T> T instantiateBean(Constructor<T> ctor, Object... args) throws InstantiationException, IllegalAccessException, InvocationTargetException {
        /**
         * make accessable
         */
        if (!Modifier.isPublic(ctor.getModifiers()) ||
                Modifier.isPublic(ctor.getModifiers()) && ctor.isAccessible()) {
            ctor.setAccessible(true);
        }
        try {
            /**
             * 实例化
             */
            return ctor.newInstance(args);
        } catch (InstantiationException e) {
            throw new InstantiationException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new IllegalAccessException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new InvocationTargetException(e.getCause());
        }
    }
}

 

转载于:https://my.oschina.net/maliang1989/blog/1586763

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值