【问题标题】:How to remove unchecked warning for Fluent interface default methods如何删除 Fluent 接口默认方法的未经检查的警告
【发布时间】:2019-11-08 10:05:39
【问题描述】:

我想知道是否有一种方法可以删除以下代码的未经检查的警告,该代码提供了一个返回自身的流畅 API。

public interface Taggable<T> {

    /**
     * Should return the underlying set that holds the tags.
     *
     * @return set
     */
    Set<String> getTags();

    @SuppressWarnings("unchecked")
    default T tag(@NotNull String... tags) {
        for (String tag : tags) {
            getTags().add(tag);
        }
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    default T untag(@NotNull String tag) {
        getTags().remove(tag);
        return (T) this;
    }

}

用法是

@Data
public class MyObject implements Taggable<MyObject> {
   private Set<String> tags;
}

MyObject t = new MyObject()
   .tag("abc")
   .tag("def");

带有抑制警告的工作示例https://repl.it/@trajano/fluent

【问题讨论】:

  • 不,T是包含集合的类型
  • 你只是想摆脱@SuppressWarnings
  • @daniu 是的(如果可能的话)到目前为止,它看起来不是。

标签: java fluent


【解决方案1】:
public interface Taggable<T extends Taggable<T>>

然后改变

(T) this

this

所以:

default Taggable<T> tag(@NotNull String... tags) {
    Collections.addAll(getTags(), tags);
    return this;
}

这就是基类 Enum(对于所有枚举类)所做的。

流畅的 API,即构建器模式,一般来说有点冗长。 但是没有像getTags 这样的工件的优点。 委托给标记/取消标记接口实现似乎更好。

【讨论】:

  • 我刚试过这个,它仍然标记为未选中。
  • 没有演员 (T) ?因为this 现在是可标记的。
  • @ArchimedesTrajano 您还需要声明default Taggable&lt;T&gt; tag(...),然后只需声明return this
  • 那么您从已删除的答案中得到相同的问题。进行此更改会产生诸如 Taggable 无法转换为 MyObject 之类的错误
  • @JoopEggen 其中 T 是一个类型变量:T 扩展 Taggable 在接口 Taggable Taggable.java:21 中声明:错误:不兼容的类型:Taggable 无法转换为 T 返回此;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多