Java - Intellij IDEA 警告枚举 getter 方法 lambda 中的 NPE

Java - Intellij IDEA warns about NPE in enum getter method lambda

我有以下枚举:

import com.google.common.collect.Maps;

public enum ServiceType {
    SOME_SERVICE (4, SomeServiceEntity.class);

    private int id;
    private Class<? extends ServiceEntity> entityClass;

    private static final Map<Integer, ServiceType> LOOKUP = Maps.uniqueIndex(
            Arrays.asList(ServiceType.values()),
            ServiceType::getId     <<=======
    );

    ServiceType(int id, Class<? extends ServiceEntity> entityClass) {
        this.id = id;
        this.entityClass = entityClass;
    }

    public int getId() {
        return id;
    }

    // and other methods....
}

这行代码被Intellij IDEA标记为:

Method reference invocation 'ServiceType::getId' may produce 'java.lang.NullPointerException'

这怎么可能,因为我有唯一的构造函数,其中包括我的 id 字段,而枚举是对象的静态列表,所以它们都应该有 id?

我怎样才能摆脱这个警告?

更新: 坚持:

private static final Map<Integer, ServiceType> LOOKUP = Arrays.stream(
        ServiceType.values()).collect(Collectors.toMap(
                ServiceType::getId, Function.identity()
        )
);

正如评论所说,您在那里使用了一个 lambda,它获取一个参数。当那个为空时,就会给出 NPE。

所以宁愿尝试这样的事情:

private static final Map<Integer, ServiceType> LOOKUP = 
  Arrays
    .stream(ServiceType.values())
    .Collectors.toMap(ServiceType::getId, Function. identity());

which ... err ... 可能会给你同样的警告。

因此,如果您真的想在此处使用流式传输,您可能必须取消该警告。