java - 如何删除 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
解决方案
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
. 委托给标记/取消标记接口实现似乎更好。
推荐阅读
- python - 如何获取谷歌日历的事件颜色
- amazon-web-services - 创建动态主体块 S3 IAM 策略
- c# - 使用上下文菜单时如何更改datagrid WPF C#中选定行的字体颜色
- azure - 使用 OAuth2.0 资源所有者密码凭证访问安全 API
- ibm-watson - IBM Watson Studio:数据图标未显示在 Cognos Dashboard 中
- javascript - 获取 ID "name" 的值总是返回 undefined
- java - 与线程相比,进程在上下文切换方面是否有任何开销?
- mysql - sql:如何创建第三列并使用相同的 id 移动 2° 结果
- javascript - 如何修改此 HTML 和 JavaScript,使其在网页上提供多个可移动项目?
- excel - Excel VBA 将单引号插入包含 16 个以上数字的列中