java serializable接口是什么?讓我們一起來了解一下吧!
java serializable接口是java程序中的serializable接口。serializable接口指的是運用其序列化功能的一個接口。如果沒有這個接口的類便不可以讓它們的任意狀態變成序列化或者逆序列化。
serializable接口的定義代碼:
public?interface?Serializable?{ }
serializable接口也被稱為標識接口,它沒有其他別的屬性與方法。標識接口的定義是不能解決實際問題僅僅具有標識功能。
序列化的定義:序列化是將對象狀態轉換為可保持或傳輸的格式的過程。與序列化相應存在的是反序列化,它將流轉換成對象。這兩個過程結合起來,可以輕松地存儲和傳輸數據。
序列化對于存儲數據的好處:支持數據傳輸,特別是遠程調用的時候。當我們需要把對象的狀態信息通過網絡傳輸或者需要將對象狀態信息持久化,以便將來使用時都需要把對象進行序列化。
實戰演練,具體代碼如下:
import?java.io.FileInputStream; ? import?java.io.FileOutputStream; ? import?java.io.IOException; ? import?java.io.ObjectInputStream; ? import?java.io.ObjectOutputStream; ? public?class?Test?{undefined ? public?static?void?main(String[]?args)?{undefined ? Person?p?=?new?Person(); ? p.setName("feige"); ? writeObj(p); ? Person?p2?=?readObj(); ? System.out.println(p2); ? } ? //?序列化 ? public?static?void?writeObj(Person?p)?{undefined ? try?{undefined ? ObjectOutputStream?objectOutputStream?=?new?ObjectOutputStream(new?FileOutputStream("E://1.txt")); ? objectOutputStream.writeObject(p); ? objectOutputStream.close(); ? }?catch?(IOException?e)?{undefined ? e.printStackTrace(); ? } ? } ? //?反序列化 ? public?static?Person?readObj()?{undefined ? Person?p?=?null; ? try?{undefined ? ObjectInputStream?objectInputStream?=?new?ObjectInputStream(new?FileInputStream("E://1.txt")); ? try?{undefined ? p?=?(Person)objectInputStream.readObject(); ? }?catch?(ClassNotFoundException?e)?{undefined ? e.printStackTrace(); ? } ? }?catch?(IOException?e)?{undefined ? e.printStackTrace(); ? } ? return?p; ? } ? }
以上就是小編今天的分享了,希望可以幫助到大家。