Java enumeration types can implement the Serializable interface for serialization and deserialization. Serialization mechanism: import the necessary libraries. Create an enumeration instance. Create an object output stream. Writes an enumeration instance to the output stream. Deserialization mechanism: import the necessary libraries. Create an object input stream. Reads an enumeration instance from the input stream.
Java enumeration type is a data type that represents a set of constant values. They are final and therefore cannot be changed. Due to their immutability, Java enumeration types can implement the Serializable
interface in order to store them in a file or send them over the network via serialization.
Serialization converts an object into a stream of bytes so that it can be stored or transmitted. To serialize an enumeration class, use the ObjectOutputStream
class. Following are the steps to serialize an enumeration class:
import java.io.FileOutputStream; import java.io.ObjectOutputStream; public class EnumSerialization { public static void main(String[] args) { // 创建枚举类的实例 Color color = Color.BLUE; // 创建对象输出流 try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("enum.ser"))) { // 将枚举实例写入输出流 out.writeObject(color); } catch (Exception e) { e.printStackTrace(); } } // 枚举类 public enum Color { RED, BLUE, GREEN } }
Deserialization converts the byte stream back into an object. To deserialize an enum class, use the ObjectInputStream
class. The following are the steps to deserialize an enumeration class:
import java.io.FileInputStream; import java.io.ObjectInputStream; public class EnumDeserialization { public static void main(String[] args) { // 创建对象输入流 try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("enum.ser"))) { // 从输入流中读取枚举实例 Color color = (Color) in.readObject(); // 打印枚举实例 System.out.println(color); } catch (Exception e) { e.printStackTrace(); } } // 枚举类 public enum Color { RED, BLUE, GREEN } }
In actual applications, enumeration serialization and deserialization can be used:
The above is the detailed content of What is the serialization and deserialization mechanism of Java enumeration types?. For more information, please follow other related articles on the PHP Chinese website!