Java 8 Stream丢失了类型信息

Wyt*_*tze 3 java java-stream

我有以下流来选择符合特定条件的对象:

    protected final Map<String, PropertyMapping> propertyMappings = new LinkedHashMap();

    public List<PropertyMapping> getPropertyMappingsByAnnotation(final Class annotation) {
        return propertyMappings.values()
            .stream()
            .filter(pm -> pm.getAnnotation(annotation) != null)
            .collect(Collectors.toList());
    }
Run Code Online (Sandbox Code Playgroud)

过滤器以某种方式导致Stream失去对流的泛型类型的跟踪,导致collect语句失败并出现以下错误:

incompatible types: java.lang.Object cannot be converted to java.util.List<PropertyMapping>
Run Code Online (Sandbox Code Playgroud)

如果我将过滤器更改为pm - > true,例如流再次起作用.导致这种行为的原因是什么方法可以避免这种情况?它可能与传入的'annotation'类有关.我试图传递一个final修饰符,看看是否能修复问题.

这是getAnnotation方法的签名:

public final <T extends Annotation> T getAnnotation(Class<T> annotationClass)
Run Code Online (Sandbox Code Playgroud)

khe*_*ood 7

我可以看到的一个显而易见的问题是,您正在尝试将普通Class变量作为参数传递给期望Class<T>where 的方法<T extends Annotation>.我想编译器无法完全识别该方法调出,并且它导致流链末尾的编译错误.如果你解决了这个问题,你的神秘问题可能就会消失.

像这样的东西:

public <T extends Annotation> List<PropertyMapping> 
    getPropertyMappingsByAnnotation(Class<T> annotation) {
Run Code Online (Sandbox Code Playgroud)