使用反射复制构造函数 [英] Copy constructor using reflection

查看:77
本文介绍了使用反射复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含100个字段的基类和一个包含2个更多字段的派生类。我想通过调用基类中的getter使Derived类中的所有100个字段都可访问,因此这就是为什么我使用继承而不是合成的原因。在Derived中,我想有一个构造函数,该构造函数会初始化Base中的所有内容:

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


推荐答案

如果您需要从其他具有相同属性(或多或少)的bean填充,您肯定可以在这里找到一些东西:

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/

特别

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

我想 BeanUtils.copyProperties(Object orig,Object dest)会为您效劳无需负担复制所有字段的麻烦。

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

这篇关于使用反射复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆