如何将派生类克隆(复制基类部分)到基类。
在我的例子中,基类是一个 JPA 实体,派生类有一些用于 swing/ui 的东西。 我认为通过 gson/json 序列化克隆应该可以工作,但有不同的问题。
Base d=new Derived();
Base b=(Base) SerializationUtils.clone(d);
System.out.println(b.getClass().getSimpleName()); //-->Derived
//hibernateSession.save(b) -> refers to derived class
除了手动将所有属性从派生复制到基类之外,还有其他简单的方法吗?
最佳答案
确保继承树的所有级别都支持 Java Beans API。现在你可以像这样编写一个特定级别的克隆器:
public <T> T specialClone( T obj, Class<T> type ) {
T result = type.newInstance();
Class<?> current = type;
while( current != null ) {
BeanInfo info = Introspector.getBeanInfo( current );
for( PropertyDescriptor pd: info.getPropertyDescriptors() ) {
Object value = pd.getReadMethod().invoke( obj );
pd.getWriteMethod().invoke( result, value );
}
current = current.getSuperClass();
}
return result;
}
请注意,您可能希望缓存读/写方法,因为方法调用是同步的。
当我做这样的事情时,我通常检查一次 bean 并创建包装这两个方法的辅助对象,这样我就可以像这样工作:
for( Helper h : get( current ) ) {
h.copy( obj, result );
}
public Helper[] get( Class<?> type ) {
... look in cache. If nothing there, create helper using PropertyDescriptors.
}
关于java - 深拷贝/克隆派生类到基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10169967/