MessagePack和不可变对象

时间:2013-07-10 19:40:58

标签: java msgpack messagepack

我有许多不可变的域对象,包含私有final字段和公共getter方法。是否可以使用MessagePack implementation for Java

序列化它们

我知道@Message注释只支持公共字段,但我希望使用@MessagePackBeans@OrdinalEnum注释。当我尝试序列化我的一个对象时,.write调用没有任何异常,但序列化失败。我在下面列出了一个完整的例子。

我有什么问题,或者我应该放弃尝试使用MessagePack吗?

import java.io.IOException;
import org.msgpack.MessagePack;
import org.msgpack.annotation.MessagePackBeans;
import org.msgpack.annotation.OrdinalEnum;

public class MsgPackTest {

  @OrdinalEnum
  public static enum MyEnum {
    A;
  }

  @MessagePackBeans
  public final static class MyObject {
    private final String myString;
    private final MyEnum myEnum;

    public MyObject(String myString, MyEnum myEnum) {
      this.myString = myString;
      this.myEnum = myEnum;
    }
    public String getMyString() {
      return myString;
    }       
    public MyEnum getMyEnum() {
      return myEnum;
    }
  }

  public static void main(String[] args) {
    final MyObject obj = new MyObject("abc", MyEnum.A);
    final MessagePack msgPack = new MessagePack();
    try {
      final byte[] bytes = msgPack.write(obj); //bytes = [-112]
      MyObject result = msgPack.read(bytes, MyObject.class);
      //Unreachable code - MessageTypeException thrown
      System.out.println("Success: " + result);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

0 个答案:

没有答案