mercredi 6 septembre 2017

Java reflection with clone

Example I have data layer after

public class DemoData implements Cloneable {

    private String name;
    private String value;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); //To change body of generated methods, choose Tools | Templates.
    }
}

I want to assign data values (DemoData) to a duplicate data (DemoData clone) layer as follows

public static void main(String[] args) {
        DemoData demoData = new DemoData();
        demoData.setName("Class Sources");
        testReflectionDemo(demoData);
    }

    private static DemoData testReflectionDemo(DemoData demoData) {
        try {
            DemoData clone = (DemoData) demoData.clone();
            clone.setName(demoData.getName());
            clone.setValue(demoData.getValue());
            return clone;
        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

I want to convert the method testReflectionDemo(DemoData demoData) to method testReflectionDemo(T t) reflection as shown below.I do not know how to continue, please help me

public <T> T testReflectionDemo(T t){
        Class<?> aClass = t.getClass();
        for (Method method : aClass.getMethods()) {

        }
        return null;
    }





Aucun commentaire:

Enregistrer un commentaire