我的枚举原始 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");