samedi 11 mai 2019

How to call clone from Cloneable object?

I need to back up a test Object's fields using Reflection.

If fieldObject is Cloneable I need to clone() it, but I can't figure out how to call clone() when it's protected in Object class.

For example, ClassroomStoryTest is a test object in runtime:

public class ClassroomStoryTest {
    private java.util.Date reconstructionTime;   // Cloneable
    private String nameOfClassroom;              // Got copy-ctor
    private Chairs chairs;                       // Not Cloneable and No copy-ctor
...
}

// test instanceof ClassroomStoryTest
var fields = test.getClass().getDeclaredFields();

var backupFields = Arrays.stream(fields).map(field -> {

            // field.setAccessible(true) + field.get(test);
            var fieldObject = accessibleGet(field, test); 

            // getDeclaredConstructor(currObj.getClass())
            var copyCtor = getConstructor(fieldObject); 

            if (fieldObject instanceof Cloneable) {
                // 'clone' has protected access in 'java.lang.Object'
                return fieldObject.clone(); // <-- Error
            } else if (copyCtor != null) {

                // copyCtor.newInstance(fieldObject)
                return createInstance(copyCtor, fieldObject);
            }
            return fieldObject;
        }).toArray();

The only solution I thought about is making clone() public in runtime, is there any other solution? I wonder if I can do something like ((CloneableObject) fieldObject).clone()?





Aucun commentaire:

Enregistrer un commentaire