Hi I have to construct an object from an object. Since the base class has more than 50 fields i dont want to do things like
//obj1 is an instance of BaseClass
DerivedClass obj2 = new DerivedClass();
obj2.setField1(obj1.getField1());
obj2.setField2(obj1.getField2())
.... so on
As you see from the title i want to downcast my object but java does not allow this. Is there a utility library or smth that provides a method like
Object convert(BaseClass obj1, DerivedClass obj2)
You can use Apache Commons BeanUtils to do this. Using its BeanUtils
class you have access to a lot of utility methods for populating JavaBeans properties via reflection.
To copy all the common/inherited properties from a base class object to a derived class object you can use its static copyProperties()
method as
BeanUtils.copyProperties(baseClassObj, derivedClassObj);
From the BeanUtils.copyProperties() docs
Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
If you don't want to use a third-party library, your next best option would be to provide a utility method on the derived class that initializes itself with all the properties of an instance of its parent class.
public void initFromParent(BaseClass obj) {
this.propOne = obj.getPropOne();
// ... and so on
}