本篇文章给大家分享的是有关如何正确的使用Kryo框架,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
使用方法如下:
</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也自动匹配:
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 h3= (HashMap)kryo.readObject(i, HashMap.class);
System.out.println(h3.get("k2"));
}
那么,我自定义的Bean又应该如何处理呢?下面给出例子:
1、先定义Bean TestBean:
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)); ,具体例子如下:
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();
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框架,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。