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.
  }
}
有帮助吗?

解决方案

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.

其他提示

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);
     }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top