Kryo框架的source已移至https://github.com/EsotericSoftware/kryo ,進入此頁面,然后點擊右邊的Download Zip按鈕,就能下載到最新版本的Kryo框架。
導入Eclipse時,記得JDK/JRE選用 JDK1.7版本,因為Kryo會引用到unsafe()對象的一些方法JDK1.7才兼容。。
先來一個String類的序列化跟還原,是不是很簡單?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
</pre><pre name= "code" class = "java" > private static void testString () { Kryo kryo= new Kryo(); String w_str1= "簡體中文,繁體中文,English" ; //把w_str1對象序列化 Output output= new Output( 1024 ); kryo.writeObject(output, w_str1); output.flush(); output.close(); byte [] w_ret= output.toBytes(); //獲得byte數據,這些數據可用作儲存、網絡傳輸等... //還原 Input input= new Input(w_ret); input.close(); String w_str2=kryo.readObject(input, String. class ); System.out.println(w_str2); } |
再來一個HashMap類的序列化跟還原,因為Kryo自帶了很多java基本類的Serializer,所以盡管不知道Serializer,Kryo也自動匹配:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public static void testHashMap() throws NoSuchAlgorithmException{ Kryo kryo= new Kryo(); HashMap h= new HashMap(); h.put( "k1" , "v1" ); h.put( "k2" , "v2" ); Output output= new Output( 1 , 1024 ); kryo.writeObject(output, h); output.close(); byte [] data=output.toBytes(); Input i= new Input(data); i.close(); HashMap h2= (HashMap)kryo.readObject(i, HashMap. class ); System.out.println(h2.get( "k2" )); } |
那么,我自定義的Bean又應該如何處理呢?下面給出例子:
1、先定義Bean TestBean:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public static class TestBean implements Serializable{ private int [] intArray; private HashMap<String,String> hashMapVal; private String strVal; public int [] getIntArray () { return intArray; } public void setIntArray ( int [] intArray) { this .intArray = intArray; } public HashMap<String, String> getHashMapVal () { return hashMapVal; } public void setHashMapVal (HashMap<String, String> hashMapVal) { this .hashMapVal = hashMapVal; } public String getStrVal () { return strVal; } public void setStrVal (String strVal) { this .strVal = strVal; } } |
2、因為這是自定義的Bean,Kryo在序列化前先要對TestBean進行注冊:kryo.register(TestBean.class,new BeanSerializer(kryo, TestBean.class)); ,具體例子如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public static void testBean() throws NoSuchAlgorithmException{ Kryo kryo= new Kryo(); kryo.register(TestBean. class , new BeanSerializer(kryo, TestBean. class )); TestBean tb1= new TestBean(); tb1.setStrVal( "test1" ); tb1.setHashMapVal( new HashMap<String,String>()); tb1.getHashMapVal().put( "k1" , "v1" ); tb1.getHashMapVal().put( "k2" , "v2" ); int [] ints= new int [ 3 ]; ints[ 0 ]= 1 ; ints[ 1 ]= 2 ; ints[ 2 ]= 3 ; tb1.setIntArray(ints); Output output= new Output( 1 , 1024 ); kryo.writeObject(output, tb1); output.close(); byte [] data=output.toBytes(); |
1
2
3
4
5
6
7
|
Input i= new Input(data); i.close(); TestBean tb2= (TestBean)kryo.readObject(i, TestBean. class ); System.out.println(tb2.strVal); System.out.println(tb2.hashMapVal.get( "k1" )); System.out.println(tb2.intArray[ 2 ]); } |
總結
是不是非常簡單?關于Kryo框架使用方法代碼示例的介紹就到這里,希望對大家有所幫助。有什么問題可以隨時留言,小編會及時回復大家的。
原文鏈接:http://blog.csdn.net/rocklee/article/details/26451739