我有一个图片
的现有内部数据模型,如下所示:
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 文件,它反射(reflect)了 Picture
类的字段,并在 test.model.protobuf
包下编译了代码,类名是 PictureProtoBuf
:
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());
但是,这很容易损坏并且依赖于枚举名称在我的内部数据模型和 Protocol Buffer 数据模型之间保持一致(这不是一个很好的假设,因为 .proto 文件中的枚举名称需要是唯一的)。如果来自内部模型的 .name()
调用与 protobuf 生成的枚举名称不匹配,我可以看到我必须在枚举上手工制作 switch 语句。
我想我的问题是我的处理方式是否正确?我是否应该放弃我的内部数据模型 (test.model.Picture
) 以支持 protobuf 生成的模型 (test.model.protobuf.PictureProtoBuf
)?如果是这样,我如何实现我在内部数据模型中所做的一些细节(例如 hashCode()
、equals(Object)
、toString( )
等)?
最佳答案
虽然现有的答案都很好,但我决定更进一步 Marc Gravell研究原型(prototype)的建议。
你可以使用原型(prototype)runtime module与动态 ObjectSchema 一起在运行时为您的内部数据模型创建模式
我的代码现在缩减为:
// Do this once
private static Schema<Picture> schema = RuntimeSchema.getSchema(Picture.class);
private static final LinkedBuffer buffer = LinkedBuffer.allocate(DEFAULT_BUFFER_SIZE);
// For each Picture you want to serialize...
Picture p = new Picture(100, 200, Picture.JPEG);
byte[] result = ProtobufIOUtil.toByteArray(p, schema, buffer);
buffer.clear();
return result;
当您的内部数据模型中有很多属性时,这是对 Google protobuf 库(参见我的问题)的重大改进。也没有我可以检测到的速度损失(无论如何,在我的用例中!)
关于java - 使用 Protocol Buffers 和内部数据模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9272623/