BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #51271同步于 2016/6/29
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

关于java自定义序列化的问题

muyundefeng
2016/6/29镜像同步3 回复
package SerialTest; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class AnotherClass implements Serializable{ private static final long serialVersionUID = -5606842333916087978L; private String propertyOne; private transient String propertyTwo; public AnotherClass(String propertyOne, String propertyTwo) { this.propertyOne = propertyOne; this.propertyTwo = propertyTwo; } private void writeObject(ObjectOutputStream o) throws IOException { o.defaultWriteObject(); o.writeObject(propertyTwo); } private void readObject(ObjectInputStream o) throws IOException, ClassNotFoundException { o.defaultReadObject(); propertyTwo = (String) o.readObject(); } public String getPropertyOne() { return propertyOne; } public String getPropertyTwo() { return propertyTwo; } } package SerialTest; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Main { public static void main(String[] args) throws Exception { AnotherClass testWrite = new AnotherClass("valueOne", "valueTwo"); FileOutputStream fos = new FileOutputStream("src/main/java/foo.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(testWrite); oos.flush(); oos.close(); AnotherClass testRead; FileInputStream fis = new FileInputStream("src/main/java/foo.txt"); ObjectInputStream ois = new ObjectInputStream(fis); testRead = (AnotherClass)ois.readObject(); ois.close(); System.out.println("--Serialized object--"); System.out.println("propertyOne: " + testWrite.getPropertyOne()); System.out.println("propertyTwo: " + testWrite.getPropertyTwo()); System.out.println(""); System.out.println("--Read object--"); //System.out.println("PropertOne" + testRead); System.out.println("propertyOne: " + testRead.getPropertyOne()); System.out.println("propertyTwo: " + testRead.getPropertyTwo()); } } AnotherClass中进行序列化的字段不是应该包括非静态与非瞬时字段吗?这样的话在序列化的过过程中不应该写入propertyTwo字段,但是为什么·在反序列化的过程中却能获得propertyTwo相关字段?请各位大神帮忙解释一下。
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
nuanyangyang机器人#1 · 2016/6/29
ObjectOutputStream的API这样说:The default!!! default!!! default!!!重要的事情要说三遍 serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.
muyundefeng机器人#2 · 2016/6/29
能细说一下吗?不太明白
muyundefeng机器人#3 · 2016/6/29
能细说一下吗?不太明白 【 在 nuanyangyang 的大作中提到: 】 : ObjectOutputStream的API这样说:The default!!! default!!! default!!!重要的事情要说三遍 serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.