Cześć.
Mam za zadanie skopiować wszystkie pola z jednego obiektu do drugiego (obiekty są takie same). Nie mogę korzystać z klasy BeanUtils.
Napisałem taką metodę, ale wyrzuca ona IllegalAccessException. Ma ktoś pomysł w czym może być problem lub jak to lepiej napisać?
public static void copyProperties(Object fromObj, Object toObj) {
Class<? extends Object> fromClass = fromObj.getClass();
Class<? extends Object> toClass = toObj.getClass();
try {
BeanInfo fromBean = Introspector.getBeanInfo(fromClass);
BeanInfo toBean = Introspector.getBeanInfo(toClass);
PropertyDescriptor[] toPd = toBean.getPropertyDescriptors();
List<PropertyDescriptor> fromPd = Arrays.asList(fromBean
.getPropertyDescriptors());
for (PropertyDescriptor propertyDescriptor : toPd) {
propertyDescriptor.getDisplayName();
PropertyDescriptor pd = fromPd.get(fromPd
.indexOf(propertyDescriptor));
if (pd.getDisplayName().equals(
propertyDescriptor.getDisplayName())
&& !pd.getDisplayName().equals("class")) {
if(propertyDescriptor.getWriteMethod() != null && pd.getReadMethod() != null)
propertyDescriptor.getWriteMethod().invoke(toObj, pd.getReadMethod().invoke(fromObj, new Object[] {}));
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}