0

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.

Higor Oliveira
  • 129
  • 2
  • 8
  • 1
    Your abstract class says that `T` should be of type `ProxyAdapter` and its `FROM` and `TO` types should be same. But your `RequestProxyAdapterResolver` changes that contract by trying to use `ProxyAdapter` with different `FROM` and `TO` types by declaring them as wildcard (which means any type). – tsolakp Aug 09 '17 at 19:22

1 Answers1

1

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>> {
Sean Van Gorder
  • 3,393
  • 26
  • 26