实现Serializable接口,编写地定义的针对transient field的加密处理方案。
package cxz.serial;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectSaver {
public static void main(String[] args) throws Exception {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
"D:\\objectFile.obj"));
Customer obj3 = new Customer("Tom", 20, "pwd");
out.writeObject(obj3);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"D:\\objectFile.obj"));
Customer somebody = (Customer) in.readObject();
in.close();
System.out.println(somebody);
}
}
package cxz.serial;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Customer implements Serializable {
private static int no;
private String name;
private transient String password;
private int age;
public Customer(String string, int i, String pwd) {
name = string;
age = i;
password = pwd;
no++;
}
public static int getNo() {
return no;
}
public String toString() {
return name + age + password + no;
}
private byte[] change(byte[] buff) {
for (int i = 0; i < buff.length; i++) {
int b = 0;
for (int j = 0; j < 8; j++) {
int bit = (buff[i] >> j & 1) == 0 ? 1 : 0;
b += (1 << j) * bit;
}
buff[i] = (byte) b;
}
return buff;
}
private static final long serialVersionUID = -5990189113322816258L;
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
byte[] buff = (byte[])in.readObject();
password = new String(change(buff));
no = in.readInt();
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(change(password.getBytes()));
out.writeInt(no);
}
}