首页 > 解决方案 > 如何删除 Fluent 接口默认方法的未经检查的警告

问题描述

我想知道是否有一种方法可以删除以下代码的未经检查的警告,该代码提供了一个返回自身的流畅 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

标签: javafluent

解决方案


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. 委托给标记/取消标记接口实现似乎更好。


推荐阅读