gpt4 book ai didi

Java 编译时出现一般错误 : "type argument is not within bounds of type-variable T"

转载 作者:行者123 更新时间:2023-12-02 12:23:36 26 4
gpt4 key购买 nike

我正在开发一个代理适配器,以使用 Java 中的泛型将请求/响应转换为另一个请求/响应。

我有一个界面:

public interface ProxyAdapter<FROM, TO> {

TO adapt(FROM o);
}

适配器的实现(仅以请求案例为例):

public interface RequestProxyAdapter<FROM, TO> extends ProxyAdapter<RequestEntity<FROM>, RequestEntity<TO>> { }

抽象类:

public abstract class ProxyAdapterResolver<U extends HttpEntity<?>, T extends ProxyAdapter<U, U>> {

private final Map<String, T> adapters;

private final T defaultAdapter;

public ProxyAdapterResolver(Collection<T> adapters, T defaultAdapter) {
this.adapters = adapters.stream()
.collect(Collectors.toMap(this::proxyNameResolver, Function.identity()));

this.defaultAdapter = defaultAdapter;
}
// other methods...
}

具体类:

@Component
public class RequestProxyAdapterResolver extends ProxyAdapterResolver<RequestEntity<?>, RequestProxyAdapter<?, ?>> {
@Autowired
public RequestProxyAdapterResolver(Collection<RequestProxyAdapter<?, ?>> allAdapters) {
super(allAdapters, a -> a);
}
}

异常发生在编译时,进入具体类RequestProxyAdapterResolver。这是堆栈跟踪:

Error:(11, 108) java: type argument br.com.afferolab.attendancelist.core.proxy.service.RequestProxyAdapter<?,?> is not within bounds of type-variable T

obs:类RequestEntity来自org.springframework.http包

异常很明显,我确实在堆栈溢出中阅读了有关此问题的一些问题。但是我找不到适合我的情况的解决方案。例如:

Java generics issue: Class "not within bounds of type-variable" error.

Type argument T is not within bounds of type-variable T(Java Generic)

Inferring a generic type from a generic type in Java (compile time error)

我花了大约三天的时间来解决这个问题。有任何想法吗?谢谢。

最佳答案

我认为问题在于 RequestEntity<?>作为第一个参数和 RequestEntity<?> 给出通配符参数的隐含上限为 RequestProxyAdapater不被视为完全相同的类型,但您要求它们全部为 U 类型.

我发现当我在让泛型协同工作时遇到困难时, ? extends? super经常会修复它。试试这个:

public abstract class ProxyAdapterResolver<U extends HttpEntity<?>, T extends ProxyAdapter<? extends U, ? extends U>> {

关于Java 编译时出现一般错误 : "type argument is not within bounds of type-variable T",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45598214/

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