Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor using reflection [closed]

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.
  }
}
like image 468
tuxx Avatar asked Feb 23 '14 18:02

tuxx


1 Answers

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.

like image 84
Jorge_B Avatar answered Sep 30 '22 12:09

Jorge_B