序列化爲什麼要實現Serializable接口

觀察這個接口可以發現這只是一個標識接口,裏面沒有任何的實現;

現在定義一個Apple類,先將其寫入到文件中,然後再讀取這個文件,看能否變爲Apple類;

package com.java.sort;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializableDemo {
	public static void main(String[] args) throws Exception{
		File file = new File("apple.class");
		ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream(file));
		Apple apple = new Apple("yellow", "1kg");
		oout.writeObject(apple);
		oout.close();
		ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file));
		Object newApple = oin.readObject();
		oin.close();
		System.out.println(newApple);
	}
}


class Apple{

	private String color;

	private String weight;

	Apple(String color,String weight){
		this.color = color;
		this.weight = weight;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public String getWeight() {
		return weight;
	}

	public void setWeight(String weight) {
		this.weight = weight;
	}
}

運行結果:

Exception in thread "main" java.io.NotSerializableException: com.java.sort.Apple
	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
	at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
	at com.java.sort.SerializableDemo.main(SerializableDemo.java:14)

採用javap -c Apple:

現在我們在Apple類上增加Serializable接口:

輸出結果:

com.java.sort.Apple@355d56d5

採用javap -c Apple:

還是錯誤,看來是java傳送對象時執行了一些操作,傳送的並不是class文件;

 

查看ObjectOutputStream源碼:

 if (obj instanceof String) {
		writeString((String) obj, unshared);
	    } else if (cl.isArray()) {
		writeArray(obj, desc, unshared);
	    } else if (obj instanceof Enum) {
		writeEnum((Enum) obj, desc, unshared);
	    } else if (obj instanceof Serializable) {
		writeOrdinaryObject(obj, desc, unshared);
	    } else {
		if (extendedDebugInfo) {
		    throw new NotSerializableException(
			cl.getName() + "\n" + debugInfoStack.toString());
		} else {
		    throw new NotSerializableException(cl.getName());
		}    
	    }

根源在:obj instanceof Serializable這一句話上;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章