通过反射获取类的创建实例

时间:2019-04-30 19:23:44

标签: java reflection

我正在尝试使用单例对象,并尝试在应用程序加载期间设置字段。但是,当我尝试设置字段时,出现类强制转换异常。否则,我将尝试投射,但是这次我使用的是newInstance,并且丢失了旧实例。

我的目标是在没有构造函数的情况下像spring一样创建bean。并在应用程序加载期间向Bean添加代理。

-不是:我不想使用构造函数。就像春天创造豆一样。

我尝试了不同的解决方案

尝试上课

field.set(classObject, object); --> throw Lang.class can not cast my.package.classObject

尝试创建新的实例

field.set(classObject.cast(classObject.newInstance), object); --> creating new intsance and i am loosing singleton programming approach.

示例代码

//here i am searching all classes and adding bean and their called classes to list.
static void loadApp() {
    try {
        List<Class> classList = PackageScanner.getClasses(ApplicationProperties.getProperty("app.package"));
        classList.forEach(item -> {
            Annotation[] t = item.getAnnotationsByType(ServiceBean.class);
            if (ArrayUtils.isNotEmpty(t)) {
                ServiceBean bean = (ServiceBean) t[0];
                if (StringUtils.isEmpty(bean.value())) {
                    BeanUtil.addBean(item.getSimpleName(), item);
                } else {
                    BeanUtil.addBean(bean.value(), item);
                }
            }
            for (Field field : item.getDeclaredFields()) {
                Annotation[] a = field.getAnnotationsByType(Bean.class);
                if (ArrayUtils.isNotEmpty(a)) {
                    try {
                        BeanUtil.addField(field.getName(), new AnnotatedFieldModel(item, field));
                    } catch (Exception e) {
                        LOGGER.error("Creatiton error ", e);
                    }
                }
            }
            item.getFields();
        });
    } catch (Exception e) {
        LOGGER.error("Package Reading problem ", e);
    }
}

//I am getting classes from list. I don't have object bcs i didnt create any object yet.
    static void addPrxoy() {
    try {
        BeanUtil.getFields().keySet().forEach(item -> {
            AnnotatedFieldModel annotatedFieldModel = BeanUtil.getField(item);
            Class clazz = BeanUtil.getBean(item);
            Object object = Proxy.newProxyInstance(clazz.getClassLoader(),
                    new Class[]{annotatedFieldModel.getField().getType()},
                    new DynamicInvocationHandler());
            annotatedFieldModel.getField().setAccessible(true);
            try {
                annotatedFieldModel.getField().set(annotatedFieldModel.getClazz(), object);
            } catch (Exception e) {
                LOGGER.error("Bean creation error", e);
            }
        });
    } catch (Exception e) {
        LOGGER.error("Package Reading problem ", e);
    }
}

0 个答案:

没有答案