![](/img/trans.png)
[英]Replace lambda expression with equivalent method in IntelliJ IDEA
[英]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标记为:
方法引用调用'ServiceType :: getId'可能会产生'java.lang.NullPointerException'
当我有唯一的构造函数包含我的id
字段和枚举是静态的对象列表所以它们都假设有id时,这怎么可能呢?
我怎么能摆脱这个警告?
UPD:坚持:
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());
哪...错误...可能会给你同样的警告。
所以,如果你真的想在这里使用流,你可能不得不压制这个警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.