Search code examples
javaeclipsegenericsjava-stream

Stream API, classes and casts


I have these two methods:

Set<Class<?>> findAllClassesUsingClassLoader(String packageName)

void addNotRetryableExceptions(Class<? extends Exception>... exceptionTypes)

This code does not compile even though it would run without any problem:

 findAllClassesUsingClassLoader("my.project.exception").stream()
     .filter(RuntimeException.class::isAssignableFrom)
     .map(x -> x.asSubclass(RuntimeException.class)) // Type mismatch: cannot convert from Class<capture#14-of ? extends RuntimeException> to Class<RuntimeException>
     .forEach(recoverer::addNotRetryableExceptions);

How do I solve this properly?


Solution

  • I tried several JDK versions from Java 8 to 17 and could not reproduce the error with javac, so this seems to be an Eclipse compiler problem.

    You can work-around it by using

    .<Class<? extends RuntimeException>>map(x -> x.asSubclass(RuntimeException.class))
    

    but I also see no reason for a compiler to infer Class<RuntimeException> here, so I think, javac is right and Eclipse’s compiler has a bug.