java 我可以在 protobuf 中定义一个常量字符串吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35698849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I define a constant string in protobuf?
提问by ytoledano
I use protobuf's enums to share values between a C++ app and a Java app. This way, the same (int
) values are shared between languages and the values are available at compile time. Can I do something similar with a string by somehow defining it in the common .proto
file?
我使用 protobuf 的枚举在 C++ 应用程序和 Java 应用程序之间共享值。这样,相同的 ( int
) 值在语言之间共享,并且这些值在编译时可用。我可以通过在公共.proto
文件中以某种方式定义字符串来做类似的事情吗?
回答by Kenton Varda
Not really.
并不真地。
There are a few hacks you can use. Neither is a great fit, and (I think) both are going away in proto3:
您可以使用一些技巧。两者都不合适,而且(我认为)两者都将在 proto3 中消失:
- Define a message with a string field and give it a default value which is your constant value. However, Protobuf 3 is removing default values, apparently.
- Use "custom options", which should probably have been called "annotations" as they are much like annotations in Java or other languages. You can declare an annotation of type string, then annotate some dummy declaration with your annotation and use the constant value. However, custom options are based on extensions which are alsoremoved in proto3, so I assume custom options have been removed too. (This is the answer offered here: https://stackoverflow.com/a/11486640/2686899.)
- 定义带有字符串字段的消息并为其指定一个默认值,即您的常量值。但是,Protobuf 3 显然正在删除默认值。
- 使用“自定义选项”,它可能应该被称为“注释”,因为它们很像 Java 或其他语言中的注释。您可以声明一个字符串类型的注释,然后用您的注释注释一些虚拟声明并使用常量值。但是,自定义选项基于在 proto3中也被删除的扩展,所以我假设自定义选项也已被删除。(这是这里提供的答案:https: //stackoverflow.com/a/11486640/2686899。)
FWIW, Cap'n Proto, an alternative to protocol buffers, does support constants. (Disclosure: I am the author of Cap'n Proto as well as most of Google's Protobuf v2.)
FWIW,Cap'n Proto是协议缓冲区的替代方案,确实支持常量。(披露:我是 Cap'n Proto 以及大部分 Google Protobuf v2 的作者。)