用序列化功能包装非序列化类型

时间:2019-07-24 00:38:30

标签: java scala serialization

给出:

trait SomeTypeNotSerializable
trait ValueProvider[T] extends java.io.Serializable {
  def get: T
}

ValueProvider[SomeTypeNotSerializable]是否可序列化?有没有一种方法可以通过包装带有函数的对象来解决不可序列化的问题?

2 个答案:

答案 0 :(得分:3)

根据规则为Serializable,但是如果您将T存储为非瞬态字段,它将在运行时失败。如果T是瞬态的,或者没有字段支持(例如,在每次调用get时创建的字段),那么您就可以了,尽管我仍然很好奇为什么要序列化一个服务对象,这不是通常的做法。

答案 1 :(得分:0)

根据我的观察,在这种情况下ValueProvider[SomeTypeNotSerializable]将无法序列化。

可以使用下面的示例代码检查该示例,该示例代码在运行时会打印:

testString is Serializable
st2 is Serializable

主类:

import java.io.Serializable;

public class Main {

    public static void main(String[] args) {

        NonSerializableThing nst = new NonSerializableThing();

        SerializableThing<NonSerializableThing> st = new SerializableThing<>();
        st.set(nst);

        if(nst instanceof Serializable) { // always false
            System.out.println("nst is Serializable");
        }

        if(st.get() instanceof Serializable) {
            System.out.println("st is Serializable");
        }

        String testString = "testString";
        SerializableThing<String> st2 = new SerializableThing<>();
        st2.set(testString);

        if(testString instanceof Serializable) { // always true
            System.out.println("testString is Serializable");
        }

        if(st2.get() instanceof Serializable) {
            System.out.println("st2 is Serializable");
        }

    }
}

其他类型:

public class NonSerializableThing {

    NonSerializableThing() {}
}

public class SerializableThing<T> implements java.io.Serializable {

    public T t;

    public SerializableThing() { }

    public void set(T t) {this.t = t;}
    public T get() {return t;}

}