序列化的对象如下
public class MixedData{
private Proto.RepeatedModel protoData;
private int normalData;
}
proto模型定义如下
message RepeatedModel {
repeated int32 data;
}
关键报错信息如下
Caused by: java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1075)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:109)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:22)
at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:679)
at com.esotericsoftware.kryo.serializers.ObjectField.read(ObjectField.java:106)
... 48 more
原因很清楚, 对于repeated字段,proto编译生成的是UnmodifiedList,kryo中没有注册UnModifiedList的序列化器,使用了CollectionSerializer去做序列化,CollectionSerializer的反序列化策略关键点如下
for (int i = 0; i < length; i++)
collection.add(kryo.readObject(input, elementClass, serializer));
这里的collection是由序列化使用的list类型决定的,在本文就是UnmodifiableCollection,一切至此明了.
一个可行的解决方案如下(未测试)
添加如下依赖
<dependency>
<groupId>de.javakaffee</groupId>
<artifactId>kryo-serializers</artifactId>
<version>0.42</version>
</dependency>
在kryo配置处注册serializer
this.register(UnmodifiableCollectionsSerializer.class);
网友评论