简体   繁体   English

Java - Intellij IDEA在enum getter方法lambda中警告NPE

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

I have following enum: 我有以下枚举:

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....
}

This line of code marked by Intellij IDEA as: 这行代码由Intellij IDEA标记为:

Method reference invocation 'ServiceType::getId' may produce 'java.lang.NullPointerException' 方法引用调用'ServiceType :: getId'可能会产生'java.lang.NullPointerException'

How is this possible while I have the only constructor which include my id field and enum is static list of objects so they all suppose to have id? 当我有唯一的构造函数包含我的id字段和枚举是静态的对象列表所以它们都假设有id时,这怎么可能呢?

How can I get rid of this warning? 我怎么能摆脱这个警告?

UPD: Sticked with: UPD:坚持:

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

As the comment says, you are using a lambda there, that gets a parameter. 正如评论所说,你在那里使用lambda,它得到一个参数。 And when that one is null, that gives an NPE. 当那个为空时,就会产生一个NPE。

So rather try something like: 所以请尝试以下方法:

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

which ... err ... might give you the same kind of warning. 哪...错误...可能会给你同样的警告。

So, if you really want to use stream'ing here, you probably have to suppress that warning. 所以,如果你真的想在这里使用流,你可能不得不压制这个警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM