Moving all fields from one object into another

838 views Asked by At

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.

3

There are 3 answers

2
aioobe On BEST ANSWER

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:

public class BetterThing implements IBetterObject {
    Thing delegate;

    public BetterThing(Thing t) {
        this.delegate = t;
    }

    // Thing methods (delegate methods)
    String thingMethodOne() {
        return delegate.thingMethodOne();
    }

    // BetterThing methods
}

This is commonly referred to as the decorator pattern.

See: Prefer composition over inheritance?

0
blafasel On

You should try to minimize the performance impact by using a library that spped up the reflective operations by caching the results. Have a look at Apache common-beanutils or Dozzer.

0
Harsh Poddar On

You may use Reflection in a way which will be less expensive. I made an application where when I run the program for the first time, I save the properties name and getter and setter methods in a map and when I need to extract the properties, I just invoke those same method passing the object to invoke it on. This has good performance than using reflection every time to get method objects when you need to clone.

The other way could be to use a serializer like the Jackson or something but that will be an expensive task to serialize and deserialize.