美文网首页
第 90 条:考虑用序列化代理代替序列化实例

第 90 条:考虑用序列化代理代替序列化实例

作者: 综合楼 | 来源:发表于2021-07-22 19:31 被阅读0次
    考虑用序列化代理代替序列化实例.jpeg
    // Serialization proxy for Period class
    private static class SerializationProxy implements Serializable {
        private final Date start;
        private final Date end;
        SerializationProxy(Period p) {
            this.start = p.start;
            this.end = p.end;
        }
        private static final long serialVersionUID = 234098243823485285L; // Any number will do (Item 87)
    
        // readResolve method for Period.SerializationProxy
        private Object readResolve() {
            return new Period(start, end); // Uses public constructor
        }
    
    }
    
    
    // writeReplace method for the serialization proxy pattern
    private Object writeReplace() {
        return new SerializationProxy(this);
    }
    
    
    // readObject method for the serialization proxy pattern
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
        throw new InvalidObjectException("Proxy required");
    }
    
    
    EnumSet
    // EnumSet's serialization proxy
    private static class SerializationProxy <E extends Enum<E>> implements Serializable {
        // The element type of this enum set.
        private final Class<E> elementType;
        // The elements contained in this enum set.
        private final Enum<?>[] elements;
        SerializationProxy(EnumSet<E> set) {
            elementType = set.elementType;
            elements = set.toArray(new Enum<?>[0]);
        }
        private Object readResolve() {
            EnumSet<E> result = EnumSet.noneOf(elementType);
            for (Enum<?> e : elements)
                result.add((E)e);
            return result;
        }
        private static final long serialVersionUID = 362491234563181265L;
    }
    
    

    相关文章

      网友评论

          本文标题:第 90 条:考虑用序列化代理代替序列化实例

          本文链接:https://www.haomeiwen.com/subject/ltbysltx.html