我在用着PropertyUtils.setProperty(对象、名称、值)Apache Commons Beanutils 的方法:
开设这些课程:
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 类“A 类”上“b.c”的 Null 属性值'
是否可以告诉 PropertyUtils 如果嵌套属性有空值,请在尝试深入之前尝试实例化它(默认构造函数)?
还有其他方法吗?
谢谢
我通过这样做解决了这个问题:
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)