Create instance from superclass instance
There is a (relatively) trivial solution!
Implement a constructor in class B
that takes an instance of class A
and copies the fields.
One of the reasons there's no generic solution in the language itself is because of the problem of deep copying.
For example, if the source object contains further Objects
, as opposed to plain types, what would the generic copy operator do? Just copy the reference (giving a shallow copy), or make real copies?
What then if one of those objects is a Collection
? Should it also copy every element of the collection, too?
The only logical conclusion would be to perform a shallow copy, but then you haven't really got a copy at all.
There's no trivial solution to this because there's no one-size-fits-all solution. Basically you don't have all the information within a B
, so you can't guarantee you would have a "sensible" B
object.
You probably just want to create a constructor in B
which takes an A
and copies all the A
data into the new B
.
If you're not scared of commons-beanutils you can use PropertyUtils
import org.apache.commons.beanutils.PropertyUtils;
class B extends A {
B(final A a) {
try {
PropertyUtils.copyProperties(this, a);
}
catch (Exception e) {
}
}
}