【问题标题】:How to use a third party non serializable object in a UDAF?如何在 UDAF 中使用第三方不可序列化对象?
【发布时间】:2019-01-03 17:48:52
【问题描述】:

我有一个具有第三方不可序列化属性的类,我需要将其发送到使用此类的一种方法的 UDAF。

由于不可序列化的属性,我无法添加“实现可序列化”,并且我不能做一个子类包装器,因为该属性在其构造函数中需要一个参数...

有什么想法吗?

public class ClassWithNoSerializableProperty implements Serializable {

    private NoSerializable property;

    public ClassWithNoSerializableProperty (String text) {
        property = new NoSerializable(text);
    }

}
public class NoSerializable {

    protected String text;

    public NoSerializable(String text) {
        this.text = text;
    }

}

【问题讨论】:

  • 您可以将其标记为transient 以将其从序列化中排除。

标签: java apache-spark serialization


【解决方案1】:

使用这个类来包装NoSerializable的构造函数

SerializedWrapper<NoSerializable> property = new SerializedWrapper(() -> new NoSerializable(text));
// call this to use it.
property.get();

/**
 * Makes an unserializable class serializable through lazy initialization.
 */
public class SerializedWrapper<T> implements Serializable {

    private SerializedConstructor<T> constructor;
    private transient T instance;

    /**
     * Creates a serializable wrapper for something.
     */
    public SerializedWrapper(SerializedConstructor<T> constructor) {
        this.constructor = constructor;
    }

    /**
     * Gets or creates an instance of T.
     */
    public T get() {
        if (instance == null){
            instance = constructor.get();
        }
        return instance;
    }

}

/**
 * Dummy interface so we don't have to do (Consumer<T> & Serializable)
 */
public interface SerializedConstructor<T> implements Serializable, Consumer<T> {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多