I have many immutable domain objects with private final fields and public getter methods. Is it possible to serialize them using the MessagePack implementation for Java?
I know the @Message
annotation only supports public fields, but I was hoping to use the @MessagePackBeans
and @OrdinalEnum
annotations. When I try and serialize one of my objects, I don't get any exception on the .write
call, but serialization fails. I've included a complete example below.
Is there anything I am doing wrong, or should I give up on trying to use 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();
}
}
}