gpt4 book ai didi

java - Java 中泛型方法的绑定(bind)不匹配

转载 作者:行者123 更新时间:2023-12-01 18:56:53 26 4
gpt4 key购买 nike

我不明白为什么会出现此编译错误

Bound mismatch: The generic method element(T) of type Resource is not applicable for the arguments (Class<Chassis>). The inferred type Class<Chassis> is not a valid substitute for the bounded parameter <T extends Resource>.

使用以下代码:

public class Resource {
protected abstract class has<T extends Resource> {
public has(T v) {}
}

protected <T extends Resource> has element(T v) {
return new has<T>(v) {};
}
}

class Car extends Resource {
has chassis = element(Chassis.class);
}

class Chassis extends Resource {
}

为什么这是无效的? Chassis延伸Resource ,那么为什么不匹配 <T extends Resource>

如何限制 element() 方法接受 Resource 类对象或任何 Resource 子类对象作为参数?

最佳答案

Chassis.classjava.lang.Class 的一个实例,仅扩展 java.lang.Object .

<T extends Resource>需要 Resource 的实际实例(或其子类之一)。

要解决此问题,您可以将方法声明更改为以下内容:

protected <T extends Resource> has element(Class<T> v) {
return new has<T>(v) {};
}

关于java - Java 中泛型方法的绑定(bind)不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13695557/

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