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.
Have you tried, using apache lib?
BeanUtils.copyProperties(child, parent)
http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html
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
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With