【问题标题】:How to properly annotate methods with generic collections using Eclipse external Annotations如何使用 Eclipse 外部注释使用通用集合正确注释方法
【发布时间】:2016-11-22 04:18:50
【问题描述】:

我正在尝试使用 Eclipse 的外部注释来注释方法 java.util.List.toArray,但我不确定如何注释返回类型。如果我的列表有以下签名:

@NonNull List<@NonNull Element>

List.toArray 应该返回:

@NonNull Element @NonNull[]

但是,如果列表可以包含可为空的元素:

@NonNull List<@Nullable Element>

List.toArray 也应该返回一个包含可为空元素的数组:

@NonNull Element @Nullable[]

我正在使用 Eclipse Neon,这可能吗? Eclipse Neon New and Noteworthy page 似乎为 List.get() 提供了一个示例,并建议我应该省略该值的无效性,但这似乎不适用于数组?这是我正在使用的外部注释定义:

class java/util/List
toArray
 <T:Ljava/lang/Object;>([TT;)[TT;
 <T:Ljava/lang/Object;>([T1T;)[T1T;

但这不起作用:

    @NonNull
    List<@NonNull String> collect = // works
    @NonNull
    String @NonNull [] array = collect.toArray(new String[0]);

collect.toArray 被标记为错误:

Null 类型安全(类型注解):'String[]' 类型的表达式需要未经检查的转换才能符合'@NonNull String []'

我该如何解决这个问题?这甚至可以与 Eclipse Neon 一起使用吗?

【问题讨论】:

  • toArray 返回作为参数传递的相同类型,并且new String[0] 没有@NonNull 注释。但请注意,数组类型和Collection 的元素类型之间没有联系,例如当collect 的类型为List&lt;Integer&gt; 时,你甚至可以写String[] array = collect.toArray(new String[0]);。如果List 为空,它甚至可以工作。关于空值,需要检查器进行特殊处理,但请注意合同是特殊的:如果数组大于集合的大小,则最后一个元素后面的数组元素将nulled out。

标签: java eclipse null-check external-annotations


【解决方案1】:

我在 Eclipse 2020-03 中找到 this advice 并关注它:我将光标放在返回类型的“T”和“[]”之间,打开上下文菜单,然后选择“注释为非空”。这达到了预期的效果,就像声明了方法一样

@NonNull <T> T[] toArray(T[] a)

生成的 List.eea 文件如下所示:

class java/util/List
toArray
 <T:Ljava/lang/Object;>([TT;)[TT;
 <T:Ljava/lang/Object;>([TT;)[1TT;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多