Kryoフレーム使用方法コード例
Kryoフレームのsourceはhttps://github.com/EsotericSoftware/kryoに移動しました。このページに入り、右のDownload Zipボタンをクリックすると、最新バージョンのKryoフレームにダウンロードできます。
Eclipseを導入する時、JDK/JREはJDK 1.7バージョンを選択したことを覚えています。Kryoはunsafe()オブジェクトのいくつかの方法JDK 1.7に引用されますので、互換性があります。
まずString類の序列化と還元は簡単ですか?
1、まずBean TestBenを定義する:
とても簡単ですか?Kryoフレームの使い方コード例について紹介します。何か問題があったらいつでもメッセージを残してください。
Eclipseを導入する時、JDK/JREはJDK 1.7バージョンを選択したことを覚えています。Kryoはunsafe()オブジェクトのいくつかの方法JDK 1.7に引用されますので、互換性があります。
まずString類の序列化と還元は簡単ですか?
</pre><pre name="code" class="java"> private static void testString () {
Kryo kryo=new Kryo();
String w_str1=" , w ,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 h2= (HashMap)kryo.readObject(i, HashMap.class);
System.out.println(h2.get("k2"));
}
では、私がカスタマイズしたビーンはどう処理すればいいですか?以下の例を示します。1、まずBean TestBenを定義する:
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 BenSerializer);具体例は以下の通りです。
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フレームの使い方コード例について紹介します。何か問題があったらいつでもメッセージを残してください。