Java内置的序列化方式

网络数据传输的是一个二进制的字节数组。把对象序列化为二进制字节数组和把二进制字节数组反序列化为对象的时间加起来,时间越少,性能越高。使用JSON 和XML的居多!

先看看String类的源码

 1public final class String implements
 2    java.io.Serializable, Comparable<String>, CharSequence {
 3    /** The value is used for character storage. */
 4    private final char value[];
 5
 6    /** Cache the hash code for the string */
 7    private int hash; // Default to 0
 8
 9    /** use serialVersionUID from JDK 1.0.2 for interoperability */
10    private static final long serialVersionUID = -6849794470754667710L;
11    //....................
12}

Java的内置序列化方式

可以看出String实现了Java的内置序列化接口Serializable,于是接下来利用String类演示一下Java的内置序列化是怎样做到的:

 1import java.io.ByteArrayInputStream;
 2import java.io.ByteArrayOutputStream;
 3import java.io.IOException;
 4import java.io.ObjectInputStream;
 5import java.io.ObjectOutputStream;
 6
 7public class Demo {
 8	public static void main(String[] args) 
 9        throws IOException, ClassNotFoundException {
10
11		String str = new String("Hello");
12		
13		// 定义一个字节数组输出流
14		ByteArrayOutputStream os = new ByteArrayOutputStream();
15		
16		// 对象输出流
17		ObjectOutputStream out = new ObjectOutputStream(os);
18
19		// 将对象写入到字节数组输出,进行序列化
20		out.writeObject(str);
21		byte[] strByte = os.toByteArray();
22
23		// 字节数组输入流
24		ByteArrayInputStream is = new ByteArrayInputStream(strByte);
25
26		// 执行反序列化,从流中读取对象
27		ObjectInputStream in = new ObjectInputStream(is);
28
29		String str2 = (String) in.readObject();
30		System.out.println(str2);
31	}
32}

mark

使用Hessian进行序列化

 1import java.io.ByteArrayInputStream;
 2import java.io.ByteArrayOutputStream;
 3import java.io.IOException;
 4import java.io.ObjectInputStream;
 5import java.io.ObjectOutputStream;
 6
 7import com.caucho.hessian.io.HessianInput;
 8import com.caucho.hessian.io.HessianOutput;
 9
10public class Demo {
11	public static void main(String[] args)
12        throws IOException {
13		String str = new String("Hello");
14		
15		// 定义一个字节数组输出流
16		ByteArrayOutputStream os = new ByteArrayOutputStream();
17		
18		//Hessian的序列化输出
19		HessianOutput ho =  new HessianOutput(os);
20		
21		ho.writeObject(str);
22		
23		byte[] strByte = os.toByteArray();
24		
25		ByteArrayInputStream is = new ByteArrayInputStream(strByte);
26		
27		//Hessioan的反序列化读取对象
28		HessianInput hi = new HessianInput(is);
29		
30		String str2 = (String)hi.readObject();
31		System.out.println(str2);	
32	}
33}

mark