mardi 19 mai 2020

Cloning field via reflection - protected access

Here is my code

public Object backUP(Class<?> testClass, Object testObject) throws Exception{
        Class<?> testC = Class.forName("testClass");  //TODO: Not sure this is right.
        Object newObj = testC.newInstance();  // this is the backed up copy of the object we are updating and calling methods for.
        Field[] fields = testObject.getClass().getDeclaredFields();

        for(int i=0; i<fields.length; i++){
            fields[i].setAccessible(true);
            if(fields[i].get(testObject) instanceof Cloneable){
               Object obj =  (fields[i].get(testObject)).clone();
               newObj.getClass().getDeclaredField(fields[i].getName()).setAccessible(true);
               newObj.getClass().getDeclaredField(fields[i].getName()).set(newObj,obj);
            }

Tried cloning field with reflection, but got message that clone has protected access




Aucun commentaire:

Enregistrer un commentaire