Search code examples
javareflectionserialversionuid

Reflection a list of object which is serializable


I have asked a question in : reflect a list object

I actually got my answer just want to understand why when do this I will hits illegalArgumentException : Can not set static final ArrayList SerialVersionUID to java.lang.long. But when I do one object reflect to another object no error.

List<ClassB> listB = (List<ClassB>) convert(listA, ArrayList.class); 

Solution

  • There is a problem with the convert method when it tries to assign a final field. I suggest you modify the convert method as follows.

        for (Field targetField : targetClass.getDeclaredFields()) {
            if (!Modifier.isFinal(targetField.getModifiers())) {
                targetField.setAccessible(true);
                Field field =
                    instance.getClass().getDeclaredField(targetField.getName());
                field.setAccessible(true);
                targetField.set(target, field.get(instance));
             }
         }