gpt4 book ai didi

java - 用 protobuf 自动生成的枚举替换字符串枚举

转载 作者:行者123 更新时间:2023-11-30 07:13:39 25 4
gpt4 key购买 nike

我的 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;
}

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

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

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

和:

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

最佳答案

您可以使用 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 (稍微向下滚动到自定义选项部分。)

关于java - 用 protobuf 自动生成的枚举替换字符串枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19241569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com