3

我的枚举原始 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
    }
}

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

enum CarModel {
    NOMODEL = 0;
    X = 1;
    XS = 2;
    XSI = 3;
    XSI2 = 4;
}

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

编辑:我如何实现以下内容:

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

和:

CarModel carModel = CarModel.fromString("XS-I.2");
4

2 回答 2

7

您可以使用 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"];
}

现在在 Java 中你可以这样做:

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

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

于 2013-10-08T21:33:19.777 回答
-1
CarModel carmodel =  Enum.valueOf(CarModel.class, "XS")

或者

CarModel carmodel =  CarModel.valueOf("XS");
于 2013-10-08T07:28:18.933 回答