Details
-
Bug
-
Status: Open
-
Major
-
Resolution: Unresolved
-
1.9.4
-
None
-
None
Description
The function BeanUtils.copyProperty(bean, name, value) shall instantiate nested properties before copying them.
Example:
class Foo { Bar bar; } class Bar { int id; }
We now have an instance of Foo where bar property is null and call:
Foo foo = new Foo(); BeanUtils.copyProperty(foo, "bar.id", 3);
This will throw an exception currently.
Workaround
In my generic copy method, i instantiate all required nested properties before. Here my implementation. In BeanUtils this could be done more lazy when the target is null.
/** * Instantiates the nested properties of the given Object with proxy Objects * with the given property fieldname. * * @param obj * @param fieldName * * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException * @throws InstantiationException */ public static void instantiateNestedProperties(final Object obj, final String fieldName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { final String[] fieldNames = fieldName.split("\\."); if (fieldNames.length == 1) return; final StringBuffer nestedProperty = new StringBuffer(); // outsource temporary variables to optimize performance String fn = null; Object value = null; PropertyDescriptor propertyDescriptor = null; Class<?> propertyType = null; Object newInstance = null; for (int i = 0; i < fieldNames.length - 1; i++) { fn = fieldNames[i]; if (i != 0) nestedProperty.append("."); nestedProperty.append(fn); value = PropertyUtils.getProperty(obj, nestedProperty.toString()); if (value == null) { propertyDescriptor = PropertyUtils.getPropertyDescriptor(obj, nestedProperty.toString()); propertyType = propertyDescriptor.getPropertyType(); newInstance = propertyType.newInstance(); PropertyUtils.setProperty(obj, nestedProperty.toString(), newInstance); } } }