testserializable2.java

来自「基于LWVCL开发的库」· Java 代码 · 共 147 行

JAVA
147
字号
/** * Test Serialization when a super class is not Serializable. * * @author Edouard G. Parmelan <egp@free.fr> */import java.io.*;public class TestSerializable2{    // this class is serializable as <init>() is not private    static class NotSerialized {	static int count = 0;	public int magic = 123;	public NotSerialized(int dummy) {	    setMagic(321);	}	NotSerialized() {	    setMagic(999);	}	private void setMagic(int magic) {	    this.magic = magic;	}    }    static class Serialized	extends NotSerialized	implements Serializable    {	static int count = 0;	public int i;	public Serialized(int i) {	    super(i);	    this.i = i;	}	public String toString() {	    return "Serialized-" + i + " magic " + magic;	}    }    // this class is not serializable as it does not have <init>()    static class NotSerializable1 {	static int count = 0;	public int magic = 123;	public NotSerializable1(int dummy) {	    setMagic(321);	}	private void setMagic(int magic) {	    this.magic = magic;	}    }    static class Serialized1	extends NotSerializable1	implements Serializable    {	static int count = 0;	public int i;	public Serialized1(int i) {	    super(i);	    this.i = i;	}	public String toString() {	    return "Serialized1-" + i + " magic " + magic;	}    }     // this class is not serializable as <init>() is private    static class NotSerializable2 {	static int count = 0;	public int magic = 123;	public NotSerializable2(int dummy) {	    setMagic(321);	}	private void setMagic(int magic) {	    this.magic = magic;	}    }    static class Serialized2	extends NotSerializable2	implements Serializable    {	static int count = 0;	public int i;	public Serialized2(int i) {	    super(i);	    this.i = i;	}	public String toString() {	    return "Serialized2-" + i + " magic " + magic;	}    }    static void test(Object a) {	System.out.println ("a = " + a);	try {	    FileOutputStream fos = new FileOutputStream ("frozen_serial");	    ObjectOutputStream oos = new ObjectOutputStream (fos);	    oos.writeObject (a);	    oos.flush ();	    FileInputStream fis = new FileInputStream ("frozen_serial");	    ObjectInputStream ois = new ObjectInputStream (fis);	    Object b = ois.readObject ();	    System.out.println ("b = " + b);	}	catch (InvalidClassException e) {	    System.out.println (e);	}	catch (Exception e) {	    e.printStackTrace();	}    }    public static void main (String argv[]) {	test(new Serialized(0));	test(new Serialized1(10));	test(new Serialized2(10));    }}/* Expected Output:a = Serialized-0 magic 321b = Serialized-0 magic 999a = Serialized1-10 magic 321java.io.InvalidClassException: Missing accessible no-arg base class constructor for TestSerializable2$Serialized1a = Serialized2-10 magic 321java.io.InvalidClassException: Missing accessible no-arg base class constructor for TestSerializable2$Serialized2*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?