您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
Java序列化支持多种数据类型,主要包括以下几类:
byteshortintlongfloatdoublecharboolean数组:
类实例:
Serializable接口的类的对象可以被序列化。包装类:
Integer, Long, Double, Float, Boolean, Character, Byte, Short等。字符串:
String类实现了Serializable接口,因此字符串对象可以被序列化。日期和时间类:
Date, Calendar, LocalDate, LocalTime, LocalDateTime等。集合框架:
ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap, TreeMap等,前提是它们的元素类型也是可序列化的。枚举类型:
Serializable接口。其他标准库类:
Serializable接口,例如File, Socket, URL等。瞬态字段(transient fields):
transient关键字修饰的字段不会被序列化。静态字段(static fields):
自定义序列化逻辑:
writeObject和readObject方法来自定义序列化和反序列化的过程。版本兼容性:
import java.io.*;
public class SerializationExample implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private transient String password; // 不会被序列化
private Date creationDate;
public SerializationExample(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
this.creationDate = new Date();
}
public static void main(String[] args) {
SerializationExample obj = new SerializationExample(1, "John Doe", "secret");
// 序列化
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.ser"))) {
oos.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.ser"))) {
SerializationExample deserializedObj = (SerializationExample) ois.readObject();
System.out.println("ID: " + deserializedObj.id);
System.out.println("Name: " + deserializedObj.name);
System.out.println("Creation Date: " + deserializedObj.creationDate);
// password字段为null,因为它没有被序列化
System.out.println("Password: " + deserializedObj.password);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
通过上述代码可以看到,transient修饰的字段password在反序列化后为null,而其他字段则被正确地序列化和反序列化。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。