用protobuf自动生成的Enum替换String Enum

Dro*_*hen 2 java string enums protocol-buffers

我的Enum原始Java代码是:

public enum CarModel {
    NOMODEL("NOMODEL");
    X("X"),
    XS("XS"),
    XSI("XS-I"); //NOTE the special - character. Can't be declared XS-I
    XSI2("XS-I.2"); //NOTE the special . character. Can't be declared XS-I.2
    private final String carModel;
    CarModel(String carModel) { 
        this.carModel = carModel;
    }

    public String getCarModel() { return carModel; }

    public static CarModel fromString(String text) {
        if (text != null) {
            for (CarModel c : CarModel.values()) {
                if (text.equals(c.carModel)) {
                    return c;
                }
            }
        }
        return NOMODEL; //default
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我使用protobuf,我将进入.proto文件:

enum CarModel {
    NOMODEL = 0;
    X = 1;
    XS = 2;
    XSI = 3;
    XSI2 = 4;
}
Run Code Online (Sandbox Code Playgroud)

从我之前的问题中,我知道我可以调用protoc生成的枚举并删除我自己的类(从而避免重复的值定义),但是我仍然需要在某个地方(在包装类或包装枚举类中)定义替代fromString()方法,将为每个枚举返回正确的字符串。我怎么做?

编辑:我如何实现以下:

String carModel = CarModel.XSI.toString(); 这将返回“ XS-I”

和:

CarModel carModel = CarModel.fromString("XS-I.2");
Run Code Online (Sandbox Code Playgroud)

Ken*_*rda 5

您可以使用Protobuf的“自定义选项”完成此操作。

import "google/protobuf/descriptor.proto";

option java_outer_classname = "MyProto";
// By default, the "outer classname" is based on the proto file name.
// I'm declaring it explicitly here because I use it in the example
// code below.  Note that even if you use the java_multiple_files
// option, you will need to use the outer classname in order to
// reference the extension since it is not declared in a class.

extend google.protobuf.EnumValueOptions {
  optional string car_name = 50000;
  // Be sure to read the docs about choosing the number here.
}

enum CarModel {
  NOMODEL = 0 [(car_name) = "NOMODEL"];
  X = 1 [(car_name) = "X"];
  XS = 2 [(car_name) = "XS"];
  XSI = 3 [(car_name) = "XS-I"];
  XSI2 = 4 [(car_name) = "XS-I.2"];
}
Run Code Online (Sandbox Code Playgroud)

现在,在Java中,您可以执行以下操作:

String name =
    CarModel.XSI.getValueDescriptor()
    .getOptions().getExtension(MyProto.carName);
assert name.equals("XS-I");
Run Code Online (Sandbox Code Playgroud)

https://developers.google.com/protocol-buffers/docs/proto#options(略微向下滚动到有关自定义选项的部分。)