開心生活站

位置:首頁 > IT科技 > 

java,serializable接口

IT科技3.27W

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

java serializable接口是什麼?讓我們一起來了解一下吧!

java serializable接口是java程序中的serializable接口。serializable接口指的是運用其序列化功能的一個接口。如果沒有這個接口的類便不可以讓它們的任意狀態變成序列化或者逆序列化。

java 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; } }

標籤:接口 java