嗨,我必须从一个对象构造一个对象。由于基类有超过 50 个字段,我不想做类似的事情
//obj1 is an instance of BaseClass
DerivedClass obj2 = new DerivedClass();
obj2.setField1(obj1.getField1());
obj2.setField2(obj1.getField2())
.... so on
正如你从标题中看到的,我想向下转换我的对象,但java不允许这样做。是否有实用程序库或提供类似
的方法Object convert(BaseClass obj1, DerivedClass obj2)
最佳答案
您可以使用 Apache Commons BeanUtils去做这个。使用其 BeanUtils 类,您可以访问许多实用方法,通过反射填充 JavaBeans 属性。
要将所有公共(public)/继承属性从基类对象复制到派生类对象,您可以使用其静态 copyProperties()
方法:
BeanUtils.copyProperties(baseClassObj, derivedClassObj);
来自BeanUtils.copyProperties()文档
Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
如果您不想使用第三方库,那么下一个最佳选择是在派生类上提供一个实用方法,该方法使用其父类实例的所有属性来初始化自身。
public void initFromParent(BaseClass obj) {
this.propOne = obj.getPropOne();
// ... and so on
}
关于java - 通过反射将基类转换为派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28324307/