标签:down keyword test pretty static details nal person number
import java.io.Serializable;
/**
* 可序列化Person对象.
* @author Ramer
* Sep 18, 2016
*/
public class SerializablePerson implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private String alia;
private Integer age;
public SerializablePerson() {
}
public SerializablePerson(String name, String alia, Integer age) {
this.name = name;
this.alia = alia;
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public void setAlia(String alia) {
this.alia = alia;
}
public void setName(String name) {
this.name = name;
}
public String getAlia() {
return alia;
}
public String getName() {
return name;
}
/**
* 序列化写入对象前会调用本方法,可调试ObjectInputStream.writeObject方法
*
* @param stream the stream
* @throws IOException Signals that an I/O exception has occurred.
*/
private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException {
// 模拟加密age属性
age = age << 2;
stream.defaultWriteObject();
}
/**
* 反序列化读取对象前会调用本方法,可调试ObjectInputStream.readObject方法.
*
* @param stream the stream
* @throws IOException Signals that an I/O exception has occurred.
* @throws ClassNotFoundException the class not found exception
*/
private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException {
stream.defaultReadObject();
// 解密age属性
age = age >> 2;
}
@Override
public String toString() {
return "Person [name=" + name + ", alia=" + alia + ", age=" + age + "]";
}
}
public void serializationTest() {
String file = "testSrc/person.ser";
SerializablePerson person = new SerializablePerson("ramer", "feng", 4);
try (FileOutputStream out = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);) {
objectOutputStream.writeObject(person);
} catch (Exception e) {
e.printStackTrace();
}
}
public void deserializationTest() {
String file = "testSrc/person.ser";
try (FileInputStream out = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(out);) {
SerializablePerson person = (SerializablePerson) objectInputStream.readObject();
System.out.println("name: " + person.getName());
System.out.println("alia: "+ person.getAlia());
System.out.println("age: " + person.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
标签:down keyword test pretty static details nal person number
原文地址:http://www.cnblogs.com/QQ846300233/p/6683853.html