What's the best way of ensuring a Function argument is serializable?

前端 未结 1 1692
醉酒成梦
醉酒成梦 2021-02-13 13:31

I\'m writing a serializable class that takes several arguments, including a Function:

public class Cls implements Serializable {
    private final C         


        
1条回答
  •  灰色年华
    2021-02-13 14:03

    In most cases the answer is: don’t.

    You may notice that most classes of the JRE, even ObjectOutputStream.writeObject do not enforce Serializable in their signature. There are simply too many APIs not specifically to Serialization where the compile-time information about an object implementing Serializable gets lost and using them together with Serialization would require lots of type casting if the latter enforced their inputs to be Serializable.

    Since one of your parameters is a Collection, you may get examples from that API:

    Collections.unmodifiableList:

    The returned list will be serializable if the specified list is serializable.

    You will find more of these operations which care to retain the Serialization capability without retaining the Serializable compile-time type on the result.

    This also applies to all non-public types, e.g. the results of Collections.emptyList(), Arrays.asList(…) and Comparator.reverseOrder(). They all are Serializable without declaring it.


    Further, every class having more use cases than just getting serialized should refrain from enforcing to be always Serializable. That would hinder the uses where no Serialization is involved.

    Regarding the Collection parameter, you may consider removing the serializable constraint at all. Normally, you protect your class against later-on changes to the collection you received. A simple solution is to copy the collection and when your doing it, you may use a type which supports Serialization.

    Even if you want to avoid copying, the Serialization itself is a copying process per se, so you can simply create custom readObject and writeObject methods storing the contents of the Collection, eliminating the need to have a Serializable collection.


    To summarize it, usually the policy is that if the user of your class intends to serialize instances of it, it’s the responsibility of the user that all components put into it are themselves Serializable.

    0 讨论(0)
提交回复
热议问题