1

我有许多具有私有最终字段和公共 getter 方法的不可变域对象。是否可以使用Java 的 MessagePack 实现对它们进行序列化?

我知道@Message注释只支持公共字段,但我希望使用@MessagePackBeansand@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();
    }
  }
}
4

0 回答 0