我有一个关于Java类字段的问题.
我有两个Java类:Parent和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
.....
}
Run Code Online (Sandbox Code Playgroud)
现在我有了一个Parent类的实例.有没有办法创建Child类的实例并复制父类的所有字段而不是逐个调用setter?
我不想这样做:
Child child = new Child();
child.setA(parent.getA());
child.setB(parent.getB());
......
Run Code Online (Sandbox Code Playgroud)
此外,Parent没有自定义构造函数,我无法在其上添加构造函数.
请给你意见.
非常感谢.
小智 21
你有没有尝试过?
BeanUtils.copyProperties(子,父)
http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html
你可以使用反射我做它并为我工作正常:
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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)