/ Published in: Java
Externalizable interface provides you an alternate to Serializable interface. In Externalizable, you specify how/what to persist.
Seralizable persists all non-transient elements using default serialize/deserialize implementation.
Seralizable persists all non-transient elements using default serialize/deserialize implementation.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
package com.test.jvm; import java.io.Externalizable; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; public class ExternalizableTest { MyTestObject testObj = new MyTestObject(); testObj.setL(12345678L); testObj.setS("hello"); // Serialize object oos.writeObject(testObj); // Deserialize object MyTestObject objRead = (MyTestObject)ois.readObject(); } } private long l; public MyTestObject() { } return s; } this.s = s; } public long getL() { return l; } public void setL(long l) { this.l = l; } @Override out.writeObject(this.s); out.writeLong(this.l); } @Override this.l = in.readLong(); } } /* #1: Output: writeExternal complete readExternal complete objRead: s=hello, l=12345678 #2: If the no-arg constructor of MyTestObject is commented out, you'll get the below error: Exception in thread "main" java.io.InvalidClassException: com.test.jvm.MyTestObject; com.test.jvm.MyTestObject; no valid constructor at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:724) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1744) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1340) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:362) at com.test.jvm.ExternalizableTest.main(ExternalizableTest.java:27) Caused by: java.io.InvalidClassException: com.test.jvm.MyTestObject; no valid constructor at java.io.ObjectStreamClass.<init>(ObjectStreamClass.java:482) at java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:321) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1117) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:337) at com.test.jvm.ExternalizableTest.main(ExternalizableTest.java:22) */
URL: http://www.dzone.com/links/r/optimizing_java_serialization_java_vs_xml_vs_json.html