我的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
}
}
现在,如果我使用protobuf,我会进入.proto文件:
enum CarModel {
NOMODEL = 0;
X = 1;
XS = 2;
XSI = 3;
XSI2 = 4;
}
来自我的earlier question我知道我可以调用protoc生成的枚举并删除我自己的类(从而避免重复的值定义)但是我仍然需要在某处定义(在包装类中?包装器枚举类?)备用fromString()
方法,它将根据枚举返回正确的字符串。我该怎么做?
编辑: 我如何实现以下内容:
String carModel = CarModel.XSI.toString();
这将返回“XS-I”
和
CarModel carModel = CarModel.fromString("XS-I.2");
答案 0 :(得分:5)
您可以使用Protobuf的"custom options"完成此操作。
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(稍微向下滚动到自定义选项部分。)
答案 1 :(得分:-1)
CarModel carmodel = Enum.valueOf(CarModel.class, "XS")
或
CarModel carmodel = CarModel.valueOf("XS");