标签:except 必须 stat ransient imp rri dex private div
package com.fgy.demo2; import java.io.Serializable; /** * 想要实现序列化,必须实现Serializable接口 */ public class Person implements Serializable { private String name; private transient Integer age; public Person() { } public Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
package com.fgy.demo2; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /** * 序列化 */ public class Demo01ObjectOutputStream { public static void main(String[] args) throws IOException { Person p = new Person("lily", 18); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\a.txt")); oos.writeObject(p); oos.close(); } }
package com.fgy.demo2; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; /** * 反序列化 */ public class Demo02ObjectInputStream { public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\a.txt")); Person obj = (Person) ois.readObject(); ois.close(); System.out.println(obj.getName() + "--" + obj.getAge()); // lily--null } }
注意:
被static修饰的成员变量不能被序列化,序列化的都是对象。
被transient修饰的成员变量不能被序列化
解决java.io.InvalidClassException异常的方式:序列化对象添加成员变量 private static final long serialVersionUID = XXXL
标签:except 必须 stat ransient imp rri dex private div
原文地址:https://www.cnblogs.com/roadlandscape/p/12168966.html