我有以下枚举:
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 ... 可能会给你同样的警告。
因此,如果您真的想在这里使用流式传输,您可能必须取消该警告。
关于Java - Intellij IDEA 在枚举 getter 方法 lambda 中警告 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56645925/