SerializableObject implements Serializable { public Object readResolve() throws ObjectStreamException { try { Constructor<? extends SerializableObject> constructor = this.getClass().getConstructor(this.getClass()); try { constructor.setAccessible(true); } catch (SecurityException ex) { logger.warn("Accessing copy constructor {} failed.", constructor, ex); } try { return constructor.newInstance(this); } catch (ReflectiveOperationException | IllegalArgumentException ex) { throw new RuntimeException("Instantiation using copy constructor failed!", ex); } } catch (NoSuchMethodException snme) { logger.debug("No copy constructor detected for class {}, trying default constructor.", this.getClass().getSimpleName()); try { SerializableObject newInstance = this.getClass().newInstance(); transferStateTo(newInstance); return newInstance; } catch (ReflectiveOperationException ex) { throw new RuntimeException("Deserialization using default constructor failed!", ex); } } }  Object readResolve(); void transferStateTo(Object dest);  }
@Test public void testReadResolve() throws Exception { SerializableOperator<Object> pre = new SerializableOperator<>(); pre.setI(10); FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(pre); oos.close(); FileInputStream fis = new FileInputStream(filename); ObjectInputStream ois = new ObjectInputStream(fis); Object post = ois.readObject(); ois.close(); assertEquals("Serialized Deserialized Objects", pre, post); }