Wednesday 20 April 2016

Effective Java Item 78: Serialization proxy

 class Period implements Serializable{  
   private final Date start;  
   private final Date end;  
   
   public Period(Date start, Date end){  
     if (start.compareTo(end) > 0){  
       throw new IllegalArgumentException(start + " after "+end);  
     }  
     this.start = start;  
     this.end = end;  
   }  
   
   public Date start(){  
     return new Date(start.getTime());  
   }  
   
   public Date end(){  
     return new Date(end.getTime());  
   }  
   
   @Override  
   public String toString() {  
     return "start "+start+ " end "+end;  
   }  
   
   private static class PeriodProxy implements Serializable{  
     private final Date start;  
     private final Date end;  
   
     PeriodProxy(Period period){  
       this.start = period.start;  
       this.end = period.end;  
     }  
   
     private Object readResolve(){  
       return new Period(start, end);  
     }  
   }  
   
   private Object writeReplace(){  
     return new PeriodProxy(this);  
   }  
   
   private void readObject(ObjectInputStream in) throws InvalidObjectException{  
     throw new InvalidObjectException("Proxy required");  
   }  
   
 }  
   
 public class SerializationProxy {  
   public static void main(String[] args) throws Exception{  
     Calendar cal1 = Calendar.getInstance();  
     cal1.set(2015, Calendar.JANUARY, 1);  
     Calendar cal2 = Calendar.getInstance();  
     cal1.set(2016, Calendar.JANUARY, 1);  
     Period period = new Period(cal1.getTime(), cal2.getTime());  
     System.out.println(period);  
     Period deserializePeriod = serializeAndDeserialize(period);  
     System.out.println(deserializePeriod);  
   }  
   
   private static <T> T serializeAndDeserialize(T serialized) throws Exception {  
     File serializeFile = new File("_serialized");  
     // serialize  
     try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(serializeFile))) {  
       out.writeObject(serialized);  
     }  
     // deserialize  
     try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(serializeFile))) {  
       @SuppressWarnings("unchecked")  
       T deserialized = (T) in.readObject();  
       return deserialized;  
     }  
   }