簡體   English   中英

Java - Intellij IDEA在enum 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標記為:

方法引用調用'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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM