gpt4 book ai didi

java - 为什么 Java 泛型不支持通配符的 OR 子句?

转载 作者:行者123 更新时间:2023-11-29 07:00:44 27 4
gpt4 key购买 nike

我正在应对一种情况,我想要一个类型的泛型

MyGeneric<T extends A | B>

即一些镜像

MyGeneric<T extends A & B>

.最后一个是允许的,因为 B 是一个接口(interface);不接受 B 作为类的原因是 Java 不支持多重继承显式

来自 Generic class that accepts either of two types我得到确认,我对泛型的 OR 子句的猜测对于 Java 是 Not Acceptable 。这意味着我对 OR 子句的猜测在语法上是不正确的,无论 B 是类还是接口(interface)。所以我想知道为什么 Java 不支持这个。还有什么比“未实现”更有力的理由吗?

---编辑---

当然有很多情况下 OR 子句可能会引起疑问(请参阅评论和答案),但看看我的案例:

public abstract class MyAbstractTask<T extends MyAbstractCommand> {
@Override
final protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
T response = null;

Gson gson = new Gson();
response = gson.fromJson(result, clazz);7
postProcess(response);
}
}
abstract void postProcess(T task);
}

在这种情况下,我正在应用模板方法模式 + 命令模式。所以 T 是命令,postProcess 负责运行它。

现在我可以拥有类似的东西了

public class MyTask extends MyAbstractTask<MyCommand> {...}

这很酷。

但是,假设您创建了一个“YourCommand”类。如果它与 MyAbstractCommand 无关,我将被迫复制报告的代码或创建一个由两个抽象命令实现的通用接口(interface)或让 YourCommand 扩展 MyAbstractCommand。如果支持 OR 子句,我可以将 YourCommand 添加到泛型的可接受参数类型列表中。

最佳答案

如果 java 泛型确实支持 OR 子句,那么评论中的问题呢:

<T extends Runnable | Callable<?>> void fun(T wtf)throws Exception{
wtf.run(); // is this a compile time error?
wtf.call(); // is this a compile time error?
}

void main(Runnable runnable, Callable<?> callable){
fun(runnable); // is this a runtime error?
fun(callable); // is this a runtime error?
}

关于java - 为什么 Java 泛型不支持通配符的 OR 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26572250/

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