Can I somehow move all field values from one object to another without using reflection? So, what I want to do is something like this:
public class BetterThing extends Thing implements IBetterObject {
public BetterThing(Thing t) {
super();
t.evolve(this);
}
}
So, the evolve
method would evolve one class to another. An argument would be <? extends <? extends T>>
where T
is the class of the object, you're calling evolve
on.
I know I can do this with reflection, but reflection hurts performance. In this case Thing
class is in external API, and there's no method that would copy all the required fields from it to another object.
As @OliverCharlesworth points out, it can't be done directly. You will either have to resort to reflection (though I wouldn't recommend it!) or a series of field-by-field assignments.
Another option though, would be to switch from inheritance to composition:
This is commonly referred to as the decorator pattern.
See: Prefer composition over inheritance?