Reputation: 129
I'm developing a proxy adapter to convert a request/response into another request/response using generics in Java.
I have a interface:
public interface ProxyAdapter<FROM, TO> {
TO adapt(FROM o);
}
Implementation of adapter (using only the request case as example):
public interface RequestProxyAdapter<FROM, TO> extends ProxyAdapter<RequestEntity<FROM>, RequestEntity<TO>> { }
Abstract class:
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...
}
Concrete class:
@Component
public class RequestProxyAdapterResolver extends ProxyAdapterResolver<RequestEntity<?>, RequestProxyAdapter<?, ?>> {
@Autowired
public RequestProxyAdapterResolver(Collection<RequestProxyAdapter<?, ?>> allAdapters) {
super(allAdapters, a -> a);
}
}
The exception happens in compilation time, into concrete class RequestProxyAdapterResolver. Here's the stack trace:
Error:(11, 108) java: type argument br.com.afferolab.attendancelist.core.proxy.service.RequestProxyAdapter<?,?> is not within bounds of type-variable T
obs: class RequestEntity is from org.springframework.http package
The exception is clear and I did read some questions about this issue in stack overflow. However I couldn't find a solution for my case. Ex:
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)
I spent about three days in that problem. Any ideas? Thanks.
Upvotes: 0
Views: 492
Reputation: 3453
I think the problem is that the RequestEntity<?>
given as the first parameter and the RequestEntity<?>
implied upper bounds of the wildcard parameters to RequestProxyAdapater
aren't being considered as the exact same type, but you're requiring them all to be type U
.
I find that when I'm having trouble getting generics to work together, a ? extends
or ? super
will often fix it. Try this:
public abstract class ProxyAdapterResolver<U extends HttpEntity<?>, T extends ProxyAdapter<? extends U, ? extends U>> {
Upvotes: 1