从Java中的父类复制字段

Kev*_*vin 15 java inheritance

我有一个关于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没有自定义构造函数,我无法在其上添加构造函数.

请给你意见.

非常感谢.

rco*_*ini 5

你可以使用反射我做它并为我工作正常:

 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)


pca*_*cao 0

您可以将字段设置为私有字段protected而不是私有字段,并直接在子类上访问它们。这有帮助吗?