我有一个现有的内部数据模型,用于表示图片
,如下所示:
package test.model;
public class Picture {
private int height, width;
private Format format;
public enum Format {
JPEG, BMP, GIF
}
// Constructor, getters and setters, hashCode, equals, toString etc.
}
我现在想使用protocol buffers将其序列化。 我编写了一个Picture.proto
文件,该文件镜像了Picture
类的字段,并且使用PictureProtoBuf
作为类名,在test.model.protobuf
包下编译了代码:
package test.model.protobuf;
option java_package = "test.model.protobuf";
option java_outer_classname = "PictureProtoBuf";
message Picture {
enum Format {
JPEG = 1;
BMP = 2;
GIF = 3;
}
required uint32 width = 1;
required uint32 height = 2;
required Format format = 3;
}
现在我假设如果我有一个要序列化并发送的Picture
,我需要创建一个PictureProtoBuf
对象,并将所有字段映射过去,如下所示:
Picture p = new Picture(100, 200, Picture.JPEG);
PictureProtoBuf.Picture.Builder output = PictureProtoBuf.Picture.newBuilder();
output.setHeight(p.getHeight());
output.setWidth(p.getWidth());
我在数据模型中使用枚举时遇到了问题。我目前使用的方法很丑陋:
output.setFormat(PictureProtoBuf.Picture.Format.valueOf(p.getFormat().name());
然而,这种方法容易出现问题并且依赖于内部数据模型和协议缓冲器数据模型之间的枚举名称一致(在.proto文件中枚举名称需要唯一,因此这不是一个很好的假设)。如果来自内部模型的.name()调用与protobuf生成的枚举名称不匹配,我可以看到自己不得不手工制作枚举switch语句。 我想知道的是,我这样做是正确的方式吗? 我是否应该舍弃我的内部数据模型(test.model.Picture),转而使用protobuf生成的模型(test.model.protobuf.PictureProtoBuf)?如果是这样,那么我怎么能实现我在内部数据模型中所做的某些良好特性(例如hashCode(), equals(Object), toString()等)?