简体   繁体   中英

Java Generic error in compilation time: “type argument is not within bounds of type-variable T”

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.

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 ? extends or ? super ? super will often fix it. Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM