【问题标题】:Apache Thrift: Can we instruct thrift to translate a SET container to Java LinkedHashSet?Apache Thrift:我们可以指示 thrift 将 SET 容器转换为 Java LinkedHashSet 吗?
【发布时间】:2015-12-18 04:48:27
【问题描述】:

来自文档:Thrift 默认将 SET 容器转换为 HashSet。我们可以改变这种行为吗?

容器 Thrift 容器是强类型容器,映射到大多数编程语言中常用和常用的容器类型。

https://thrift.apache.org/docs/types:

共有三种容器类型: list:元素的有序列表。转换为 STL 向量、Java ArrayList、脚本语言中的本机数组等。 set:一组无序的唯一元素。转换为 STL 集合、Java HashSet、Python 中的集合等。注意:PHP 不支持集合,因此它被视为类似于列表

【问题讨论】:

  • 我已经知道可以在thrift生成的java类中将类型改为LinkedHashSet。但它在我们的案例中没有用,因为我们在构建过程中每次都生成/替换节俭类。

标签: java thrift


【解决方案1】:

sorted_containers 选项切换到

  • TreeMapmap<>
  • TreeSetset<>

在调用 Thrift 编译器时要指定选项,如下所示:

$ thrift  -gen java:sorted_containers  myfile.thrift

这里是适用于 Java 的所有选项(当前的 master 分支,thrift -help 揭示了更多信息)

 java (Java):
    beans:           Members will be private, and setter methods will return void.
    private-members: Members will be private, but setter methods will return 'this' like usual.
    nocamel:         Do not use CamelCase field accessors with beans.
    fullcamel:       Convert underscored_accessor_or_service_names to camelCase.
    android:         Generated structures are Parcelable.
    android_legacy:  Do not use java.io.IOException(throwable) (available for Android 2.3 and above).
    option_type:     Wrap optional fields in an Option type.
    java5:           Generate Java 1.5 compliant code (includes android_legacy flag).
    reuse-objects:   Data objects will not be allocated, but existing instances will be used (read and write).
    sorted_containers:
                     Use TreeSet/TreeMap instead of HashSet/HashMap as a implementation of set/map.
    generated_annotations=[undated|suppress]:
                     undated: suppress the date at @Generated annotations
                     suppress: suppress @Generated annotations entirely

其他选项不可用。 C++ 生成器支持注释,Java 似乎不是这样。我有没有提到we accept patches

【讨论】:

  • @JensG,类似于 sorted_containers 选项,有没有办法可以使用 ConcurrentHashMap 而不是 HashMap 实现?我们需要这个来防止地图中出现空键。
  • Link to source 不,只有我上面写的。但是,如果您认为这是一个很好的补充并且想要这样做 - 我们接受拉取请求! C++ 生成器有一个通过 IDL 注释指定类的选项,也许这可能是一种方法。问题?邮件列表!
  • @JensG,我们可以为Java生成器添加这个选项吗?