是否可以使用Commons Bean Utils自动实例化嵌套属性? [英] Is it possible automatically instantiation of a nested Property with Commons Bean Utils?

查看:330
本文介绍了是否可以使用Commons Bean Utils自动实例化嵌套属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Apache Commons Bean Utils的 PropertyUtils.setProperty(object,name,value)方法:

I'm using PropertyUtils.setProperty(object, name, value) method of Apache Commons Bean Utils:

提供这些课程:

public class A {
    B b;
}

public class B {
    C c;
}

public class C {
}

这:

A a = new A();
C c = new C();
PropertyUtils.setProperty(a, "b.c", c); //exception

如果我尝试得到: org.apache.commons.beanutils.NestedNullException:Bean类'class A '

是否可以告诉PropertyUtils,如果嵌套属性具有null值,请尝试实例化它(默认构造函数),然后再尝试做更深入的研究?

Is it possible to tell PropertyUtils that if a nested property has a null value try to instantiate it (default constructor) before trying to go deeper?

还有其他方法吗?

谢谢

推荐答案

我是通过以下方式解决的:

I solved it by doing this:

private void instantiateNestedProperties(Object obj, String fieldName) {
    try {
        String[] fieldNames = fieldName.split("\\.");
        if (fieldNames.length > 1) {
            StringBuffer nestedProperty = new StringBuffer();
            for (int i = 0; i < fieldNames.length - 1; i++) {
                String fn = fieldNames[i];
                if (i != 0) {
                    nestedProperty.append(".");
                }
                nestedProperty.append(fn);

                Object value = PropertyUtils.getProperty(obj, nestedProperty.toString());

                if (value == null) {
                    PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(obj, nestedProperty.toString());
                    Class<?> propertyType = propertyDescriptor.getPropertyType();
                    Object newInstance = propertyType.newInstance();
                    PropertyUtils.setProperty(obj, nestedProperty.toString(), newInstance);
                }
            }
        }
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    }
}

这篇关于是否可以使用Commons Bean Utils自动实例化嵌套属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆