rameshmani
rameshmani

Reputation: 825

deepcopy/clone derived class to base class

How can I clone (copy base class part) a derived class to base class.

In my case base class is a JPA entity and derived class have some stuff for swing/ui. I thought clone via gson/json serialization should work,but have different issue with that.

Base d=new Derived();
Base b=(Base) SerializationUtils.clone(d);
System.out.println(b.getClass().getSimpleName());   //-->Derived
   //hibernateSession.save(b) -> refers to derived class

Is there any simple way other than manually copying all properties from derived to base?

Upvotes: 0

Views: 790

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328614

Make sure all levels of the inheritance tree support the Java Beans API. Now you can write a certain-level cloner like this:

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

Note that you might want to cache the read/write methods because the method calls are synchronized.

When I do stuff like this, I usually examine the beans once and create helper objects that wrap the two methods so I can work like this:

for( Helper h : get( current ) ) {
    h.copy( obj, result );
}

public Helper[] get( Class<?> type ) {
    ... look in cache. If nothing there, create helper using  PropertyDescriptors.
}

Upvotes: 1

Related Questions