transient关键字–瞬态关键字
static关键字:静态关键字
静态优先于非静态加载到内存中(静态优先于对象进入到内存中)
被static修饰的成员变量不能被序列化的,序列化的都是对象
transient关键字:瞬态关键字
被transient修饰成员变量,不能被序列化
static
public class Person implements Serializable { String name = "张三"; static int age = 18; @Override public String toString() { return "Person{" + "name='" + name + '/'' + '}'; } } public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d://d.txt")); Object o = ois.readObject(); ois.close(); System.out.println(o); }
transient
public class Person implements Serializable { static String name = "张三"; transient int age = 18; @Override public String toString() { return "Person{" + "age=" + age + '}'; } } public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d://d.txt")); Object o = ois.readObject(); ois.close(); System.out.println(o); }
InvalidClassException异常-原理和解决方案
public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream onb = new ObjectInputStream(new FileInputStream("D://b.txt")); Object o = onb.readObject(); onb.close(); System.out.println(o); Person p =(Person) o; System.out.println(p.getName()+p.getAge()); }
Exception in thread"main" java.io.InvalidClassException: De_07.Person; local class incompatible: stream classdesc serialVersionUID = -647205755314169615, local class serialVersionUID = 7753234627784513054 at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:699) at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1885) at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1751) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2042) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431) at De_07.fanxulie.main(fanxulie.java:10)
解决方案:
private static final long serialVersionUID = 1L;
加上这句话之后无论你怎么改都不会报InvalidClassException异常的,先序列化,再反序列化
原创文章,作者:dweifng,如若转载,请注明出处:https://blog.ytso.com/tech/java/273994.html