标签:可扩展 int persist lan tee arraylist 反序 编码 tran
概况
序列化的作用
序列化例子
1
2
3
4
5
|
FileOutputStream f = new FileOutputStream( "tmp.o" ); ObjectOutput s = new ObjectOutputStream(f); s.writeObject( "test" ); s.writeObject( new ArrayList()); s.flush(); |
反序列化例子
1
2
3
4
|
FileInputStream in = new FileInputStream( "tmp.o" ); ObjectInputStream s = new ObjectInputStream(in); String test = (String)s.readObject(); List list = (ArrayList)s.readObject(); |
serialVersionUID 有什么用
在序列化操作时,经常会看到实现了 Serializable 接口的类会存在一个 serialVersionUID 属性,并且它是一个固定数值的静态变量。比如如下,这个属性有什么作用?其实它主要用于验证版本一致性,每个类都拥有这么一个 ID,在序列化的时候会一起被写入流中,那么在反序列化的时候就被拿出来跟当前类的 serialVersionUID 值进行比较,两者相同则说明版本一致,可以序列化成功,而如果不同则序列化失败。
1
|
private static final long serialVersionUID = -6849794470754667710L; |
父类序列化什么情况
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
public class Father { public int f; public Father() { } } public class Son extends Father implements Serializable { public int s; public Son() { super (); } } |
哪些字段会序列化
1
2
3
4
5
6
7
|
public class A implements Serializable { String name; String password private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField( "name" , String. class )}; } |
枚举类型的序列化
Externalizable 接口作用
1
2
3
4
5
6
|
public interface Externalizable extends java.io.Serializable { void writeExternal(ObjectOutput out) throws IOException; void readExternal(ObjectInput in) throws IOException, ClassNotFoundException; } |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
|
public class ExternalizableTest implements Externalizable { public String value = "test" ; public ExternalizableTest() { } public void writeExternal(ObjectOutput out) throws IOException { Date d = new Date(); out.writeObject(d); out.writeObject(value); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { Date d = (Date) in.readObject(); System.out.println(d); System.out.println((String) in.readObject()); } } |
写入时替换对象
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
|
class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this .name = name; this .age = age; } private Object writeReplace() throws ObjectStreamException { Object[] properties = new Object[ 2 ]; properties[ 0 ] = name; properties[ 1 ] = age; return properties; } } |
1
2
|
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( "test.o" )); Object[] properties = (Object[]) ois.readObject(); |
读取时替换对象
01
02
03
04
05
06
07
08
09
10
11
12
13
|
class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this .name = name; this .age = age; } private Object readResolve() throws ObjectStreamException { return 2222 ; } } |
1
2
|
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( "test.o" )); Object o = ois.readObject(); |
标签:可扩展 int persist lan tee arraylist 反序 编码 tran
原文地址:https://www.cnblogs.com/zhuxiaopijingjing/p/12268123.html