您好,登录后才能下订单哦!
在 Java 中,你可以通过实现 java.io.Serializable
接口来自定义序列化机制
Serializable
接口:import java.io.Serializable;
public class CustomObject implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public CustomObject(String name, int age) {
this.name = name;
this.age = age;
}
// getter 和 setter 方法
}
这里,我们创建了一个名为 CustomObject
的类,并实现了 Serializable
接口。同时,我们定义了一个 serialVersionUID
字段,它是用于序列化版本控制的。
为了自定义序列化和反序列化过程,我们需要实现 java.io.Externalizable
接口,该接口扩展了 Serializable
接口并添加了两个方法:writeExternal(ObjectOutput out)
和 readExternal(ObjectInput in)
。
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class CustomObject implements Externalizable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public CustomObject(String name, int age) {
this.name = name;
this.age = age;
}
// getter 和 setter 方法
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(name);
out.writeInt(age);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = in.readUTF();
age = in.readInt();
}
}
在上面的示例中,我们实现了 writeExternal
和 readExternal
方法,以便在序列化和反序列化过程中使用自定义逻辑。
ObjectOutputStream
和 ObjectInputStream
进行序列化和反序列化:现在我们可以使用 ObjectOutputStream
和 ObjectInputStream
对 CustomObject
实例进行序列化和反序列化。
import java.io.*;
public class CustomSerializationExample {
public static void main(String[] args) {
CustomObject obj = new CustomObject("John Doe", 30);
try {
// 序列化
FileOutputStream fileOut = new FileOutputStream("customObject.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in customObject.ser");
// 反序列化
FileInputStream fileIn = new FileInputStream("customObject.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
CustomObject deserializedObj = (CustomObject) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized object...");
System.out.println("Name: " + deserializedObj.getName());
System.out.println("Age: " + deserializedObj.getAge());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
在上面的示例中,我们首先创建了一个 CustomObject
实例,然后使用 ObjectOutputStream
将其序列化到文件 customObject.ser
中。接下来,我们使用 ObjectInputStream
从文件中反序列化对象,并将其转换回 CustomObject
类型。最后,我们打印出反序列化对象的属性值。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。