List <ClassA> listA; List <ClassB> listB;
Can I use reflection to reflect listA into listB? I got below code but only reflect an object
public static <A, B> B convert(A instance,
Class<B> targetClass) throws Exception {
B target = (B)targetClass.newInstance();
for (Field targetField : targetClass.getDeclaredFields()) {
targetField.setAccessible(true);
Field field =
instance.getClass().getDeclaredField(targetField.getName());
field.setAccessible(true);
targetField.set(target, field.get(instance));
}
return target;
}
In general the
convertmethod is not likely to work (forLists or any other type).Calling
Field.setAccessible(true)allows read and write access to private fields but will not allow modification offinalfields viaField.set()(anIllegalAccessException: Field is finalexception is thrown).Depending on the implementation of
Listyou are trying to copy this may prevent it from working correctly. For example, usingArrayListsuch as:fails when trying to copy
serialVersionUID.The following change to the posted code gets round this problem for
static final serialVersionUIDinArrayList:However, the next problem is that the
convertmethod is performing a shallow copy. ForLists of different types this altered version ofconvertmay appear to work correctly but it does not convert theClassAobjects in the list toClassB(the unchecked cast above hides this). This will likely causeClassCastExceptions to be thrown later in the application.Fixing this problem can be achieved by adding another method to wrap
convert:This will then need to be called as: