简体   繁体   English

将所有字段从一个对象移动到另一个对象

[英]Moving all fields from one object into another

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. 因此, evolve方法会将一个类演变为另一个类。 An argument would be <? extends <? extends T>> 一个论点是<? extends <? extends T>> <? extends <? extends T>> <? extends <? extends T>> where T is the class of the object, you're calling evolve on. <? extends <? extends T>>其中T是对象的类,你正在调用evolve

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. 在这种情况下, Thing类在外部API中,并且没有方法可以将所有必需的字段从它复制到另一个对象。

As @OliverCharlesworth points out, it can't be done directly. 正如@OliverCharlesworth指出的那样,它无法直接完成。 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? 请参阅: 首选组合而不是继承?

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 . 看看Apache common-beanutilsDozzer

You may use Reflection in a way which will be less expensive. 您可以以更便宜的方式使用Reflection。 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. 我创建了一个应用程序,当我第一次运行程序时,我在地图中保存属性名称和getter和setter方法,当我需要提取属性时,我只是调用那些传递对象的相同方法来调用它。 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. 另一种方法可能是使用像Jackson这样的序列化程序,但序列化和反序列化将是一项昂贵的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM