主要談一談Java中的序列化問題,包括Serializable與Externalizable介紹以及一些項目中的用法。
1、序列化是什麼意思?用來幹嘛的
2、Java中提供的默認序列化Serializable
package com.ztesoft.ser;
public class User {
private int id;
private String name;
private String passwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
接着我們寫個測試類,將這個對象序列化到磁盤中@Test
public void serializWrite(){
User user = new User(1, "dgh", "123456");
File file = new File("D:/user.info");
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(oos);
}
}
接着就報了一個異常:java.io.NotSerializableException: com.ztesoft.ser.User2.1、序列化ID的問題 serialVersionUID
2.2、靜態變量的序列化
2.3、父類序列化與transient關鍵字
2.4、對敏感字段的加密
private void writeObject(ObjectOutputStream out) {
try {
// 這裏可以加密
out.writeObject(passwd);
} catch (IOException e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream in) {
try {
// 這裏就可以解密了
passwd = (String) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
}
之後我們調用測試方法,發現結果是:2.6、單例模式與序列化
package com.ztesoft.ser;
public class Singleton implements java.io.Serializable {
/** */
private static final long serialVersionUID = 780762366800963430L;
public static Singleton INSTANCE = new Singleton();
// 私有構造器
private Singleton() { }
}
第二步:寫個測試方法,測試一下看看結果public void singletonTest(){
Singleton s1 = Singleton.INSTANCE;
File file = new File("D:/singleton.info");
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
// 序列化對象到硬盤
oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(s1);
// 反序列化
byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
Singleton s2 = (Singleton) in.readObject();
System.out.println(s1 == s2);
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(oos);
IOUtils.closeQuietly(ois);
}
}
3、Externalizable接口的使用
public interface Externalizable extends java.io.Serializable {
void writeExternal(ObjectOutput out) throws IOException;
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
}
這個接口繼承了Serializable接口,並有兩個方法,一個write一個read。其實和我們的readObject與writeObject一樣的啦。