Reputation: 6292
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.
Upvotes: 21
Views: 17418
Reputation: 361
Have you tried, using apache lib?
BeanUtils.copyProperties(child, parent)
http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html
Upvotes: 33
Reputation: 1337
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
}
}
}
}
Upvotes: 7
Reputation: 131
Did you try do this due reflection? Technicaly you invoke setters one by one but you don't need to know all names of them.
Upvotes: 1
Reputation: 24780
You can create a Child
constructor that accepts a Parent. But there, you will have to set all the values one by one (but you can access the Child attributes directly, without set).
There is a workaround with reflection, but it only adds complication to this. You don't want it just for save some typing.
Upvotes: 0
Reputation: 15965
You can set your fields as protected
instead of private and access them directly on the child class. Does that help?
Upvotes: 0