Java general chaos

I use two interfaces:

public interface Receiver<T> { public void receive(T obj); public Set<Class<? extends T>> getInterests(); } public interface Distributor<T> extends Receiver<T> { public void register(Receiver<T> receiver); } 

My problem is that I want to register a Distributor in a Distributor, for example. Distributor<Object> == register ==> Distributor<String>

My first thought was to change the register method to register(Receiver<? extends T> receiver). But if I want to get classes, then the receiver will be indexed in the getInterests method will return something like Set<Class<? extends ? extends T>> Set<Class<? extends ? extends T>> Set<Class<? extends ? extends T>> . Indirect I'm getting something like Set<Class<? extends T>> Set<Class<? extends T>> , but I experienced that transitive wildcards are not possible in Java.

Anyone have an idea?

EDIT: As an example:

 public void register(Receiver<? extends T> receiver){ Set<Class<? extends T>> interests = receiver.getInterests(); //Problem because receiver.getInterests is //Set<Class<? extends ? extends T>> ... } 
+7
java generics
source share
2 answers

Your problem is that Java generics are completely invariant if you don't make them an option with ? extends ? extends or ? super ? super wildcards.

A Set<Class<? extends T>> Set<Class<? extends T>> can only contain expressions of exactly compile time type Class<? extends T> Class<? extends T> . Class<String> is not the same type as Class<? extends T> Class<? extends T> (even if it is converted to this type).

Do you need a set that can contain any type that can be converted to Class<? extends T> Class<? extends T> .

Will it be Set<? extends Class<? extends T>> Set<? extends Class<? extends T>>

+7
source share

You can add a helper method that uses a type variable instead of a template

 public void register(Receiver<? extends T> receiver) { register2(receiver); } private <S extends T> void register2(Receiver<S> receiver) { Set<Class<? extends S>> interests = receiver.getInterests(); ... } 

Method, on the other hand

  public Set<Class<? extends T>> getInterests(); 

probably intended to return a covariant Set or read-only. Ideally, use a wildcard

  public Set<? extends Class<? extends T>> getInterests(); 

but I know there are too many damn permutations ...

+1
source share

All Articles