Search code examples
javagenericstype-parameter

Can the type parameter be a reference in Java?


I need a method like the following:

methodA(Class<? extends ClassA> clzz, Consumer<? extends ClassA> consumer) {
   //... AKKA message handler
   .match(clzz, s -> consumer.accept(s);)
}

This won't compile and I know why, what I want is something like:

TypeParameter T = ? extends ClassA;
methodA(Class<T> clzz, Consumer<T> consumer){//...}

Is there a way to do this?


Solution

  • Do you mean something like this?

    <T extends ClassA> methodA(Class<T> clzz, Consumer<T> consumer) {
       //... AKKA message handler
       .match(clzz, s -> consumer.accept(s);)
    }
    

    (Note that you can make it more flexible using Consumer<? super T>)