Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy fields from its parent class in Java

I have a question regarding Java class fields.

I have two Java classes: Parent and Child

class Parent{
    private int a;
    private boolean b;
    private long c;

    // Setters and Getters
    .....
}


class Child extends Parent {
    private int d;
    private float e;

    // Setters and Getters
    .....
}

Now I have an instance of the Parent class. Is there any way to create an instance of the Child class and copy all the fields of the parent class without calling the setters one by one?

I don't want to do this:

   Child child = new Child();
   child.setA(parent.getA());
   child.setB(parent.getB());
   ......

Also, the Parent does not have a custom constructor and I cannot add constructor onto it.

Please give you opinions.

Many thanks.

like image 881
Kevin Avatar asked Aug 31 '12 14:08

Kevin


2 Answers

Have you tried, using apache lib?

BeanUtils.copyProperties(child, parent)

http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html

like image 89
mwikblom Avatar answered Nov 20 '22 10:11

mwikblom


you can use reflection i do it and work fine for me:

 public Child(Parent parent){
    for (Method getMethod : parent.getClass().getMethods()) {
        if (getMethod.getName().startsWith("get")) {
            try {
                Method setMethod = this.getClass().getMethod(getMethod.getName().replace("get", "set"), getMethod.getReturnType());
                setMethod.invoke(this, getMethod.invoke(parent, (Object[]) null));

            } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                //not found set
            }
        }
    }
 }
like image 7
rcorbellini Avatar answered Nov 20 '22 08:11

rcorbellini