gpt4 book ai didi

java - 静态通用接口(interface)实现

转载 作者:行者123 更新时间:2023-12-01 08:07:21 25 4
gpt4 key购买 nike

我有一个简单的界面:

interface Predicate<T> {

boolean accepts(T in);

}

现在我还想提供以下形式的内容:

interface Predicate<T> {

public static Predicate<T> ALL = new Predicate<T>(){ ... }

boolean accepts(T in);

}

上述形式是不合法的。有没有一种方法可以提供可以键入的通用实现,即在多个上下文中我可以说 Predicate.ALL,有点像 Collections.EMPTY_SET

更新:我的意思是界面...

最佳答案

您可以像 Collections.emptySet() 一样使用类型推断(请注意,Collections.EMPTY_SET 不使用泛型)。

来自集合:

public static final Set EMPTY_SET = new EmptySet();

public static final <T> Set<T> emptySet() {
return (Set<T>) EMPTY_SET;
}

你可以这样模仿:

public static Predicate ALL = new Predicate(){ ... }   

public static final <T> Predicate<T> all() {
return (Predicate<T>) ALL;
}

关于java - 静态通用接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20564647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com