Search code examples
javareflectionclonecopy-constructor

Copy constructor using reflection


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.
  }
}

Solution

  • 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.