Copy constructor using reflection [closed]

不羁岁月 提交于 2019-12-23 10:14:29

问题


I have a Base class with 100 fields and a Derived class with 2 more fields. I want to have all the 100 fields accessible in the Derived class by calling the getters in the Base class, so that's why I'm using inheritance and not composition. In Derived I want to have a constructor which initializes everything from Base:

class Base {
  ... // 100 fields.
}

class Derived extends Base {
  ... // 2 more fields.
  Derived (Base base) {
    ... // Initialize here all 100 fields from base. Don't care about my 2 fields, can have default values.
  }
}

回答1:


If you need to populate a bean from some other having the same properties (more or less), you surely can find something here:

http://commons.apache.org/proper/commons-beanutils/

Specifically

http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.1/apidocs/org/apache/commons/beanutils/BeanUtils.html

I guess BeanUtils.copyProperties(Object orig, Object dest) will do what you need without the burden to copy all your fields.




回答2:


If a Constructor already exists in the Base class that initialises your grotesque amount of fields, then you can call super, and access that constructor.

Example

public class Parent {

    public Parent(String field1, String field2) {
       // Creates parent.
    }
}

public class Child extends Parent {

     public Child(String field1, String field2)
     {
        super(field1, field2);
     }
}


来源:https://stackoverflow.com/questions/21972423/copy-constructor-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!