ObjectOutputStream and ObjectInputStream 序列化 transient
2019-06-11 19:14
1756 查看
对象
内存------>硬盘文件中(序列化) ObjectOutputStream 序列化java对象 Serial
硬盘文件----->内存(反序列化)将硬盘中的数据"反序列化 "到内存地址 DeSerial
Compile 编译(java------>class) DeCompile 反编译
序列化 Serial
[code]import java.io.Serializable;//该接口是一个可序列化的 没有任何方法,是一个标识接口 像这样的接口还有Cloneable public class User implements Serializable { String name; public User(String name) { super(); this.name = name; } public String toString() { return "User [name=" + name + "]"; } }
[code]public class ObjectInputStream01 { public static void main(String[] args) throws FileNotFoundException, IOException { User u = new User("lili"); //创建流 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\ppp\\qpqp.txt")); //写 oos.writeObject(u); oos.flush(); oos.close(); } }
标识接口的作用,:标识的作用
JVM看到某个对象实现了标识接口会对它进行“特殊待遇”
待遇:会给该类添加一个属性,static final long serialVersionUID = (序列化版本号)
改变类会覆盖原有的序列化版本号
[code]public class User01 implements Serializable{ //自己写一个序列化版本号 static final long serialVersionUID = 123123132L; String name; }
不让系统自动生成,自己写一个序列化版本号
不管你的类如何升级,序列号都是一样的,就不会产生类的兼容问题
反序列化
[code]//反序列化 public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\ppp\\qpqp.txt")); //反序列化 Object o = ois.readObject(); System.out.println(o); ois.close(); }
transient不参加序列化
因为transient不参加序列化,所以在ObjectInputStream反序列化的时候name = null;
[code]public class User01 implements Serializable{ //自己写一个序列化版本号 static final long serialVersionUID = 123123132L; //如果不想让该属性参加序列化,需要使用transient修饰 transient String name; User01 (String name){ this.name = name; } public String toString() { return "User01 [name=" + name + "]"; } }
相关文章推荐
- 2019-06-11:appium+pytest中,PageObject设计模式的使用
- 对象关系映射(Object Relational Mapping,简称ORM)
- Maven编译工作流程 POM(Project Object M 4000 odel)
- 对象(Object)常用方法,对象拷贝
- 处理对象和驼峰命名法(Objective-C)
- 函数对象(function object)
- Object类入门这一篇就够了!
- Objective-C的对象复制
- Objective C - 类的使用
- Object of type Decimal is not JSON serializable(decimal类型的对象不可JSON序列化)
- FoveaBox: Beyond Anchor-based Object Detector解读 (三)(完结)
- Object.freeze()
- JSONObject.fromObject() 转换时的日期处理问题
- JsonObject引用需要的jar包。
- net.sf.json.JSONArray与net.sf.json.JSONObject方法总结
- Error: Plugin/Preset files are not allowed to export objects, only functions
- Invalid configuration object
- JS数组Object.keys()方法的使用示例
- 对象(Object)常用方法,对象拷贝
- Object常用方法、对象拷贝