mardi 12 juillet 2016

How to make a deep copy of an object of a generated final class using Reflection API

I found a useful method here
but it fails to work with classes with array members e.g.

public class Test {
    int [] arr = new int[2];
}

Full code from the answer mentioned above
with my failing attempts to instantiate new array:

public static Object cloneObject(Object _obj) {
    try {
        // begin my changes
        Object copy = null;
        if (!_obj.getClass().isArray())
            copy = _obj.getClass().newInstance();
        else {
            int len = Array.getLength(_obj);
            Class type = _obj.getClass().getComponentType();
            // Next line fails with: Compiler(syntax) error
            // copy = (type.getClass()[])Array.newInstance(_obj.getClass(), len);
            // Next line fails with: "InstantiationException: int cannot be instantiated"
            // copy = _obj.getClass().getComponentType().newInstance();
            // how then?
        }
        // end my changes
        for (Field field : _obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            if (field.get(_obj) == null || Modifier.isFinal(field.getModifiers()))
                continue;
            if (field.getType().isPrimitive() ||
                field.getType().equals(String.class) ||
                field.getType().getSuperclass().equals(Number.class) ||
                field.getType().equals(Boolean.class)
            )
                field.set(copy, field.get(_obj));
            else {
                Object child = field.get(_obj);
                if (child == _obj)
                    field.set(copy, copy);
                else
                    field.set(copy, cloneObject(field.get(_obj)));
            }
        }
        return copy;
    } catch (Exception _e){
        return null;
    }
}

Is it even possible to achieve?





Aucun commentaire:

Enregistrer un commentaire