简体   繁体   中英

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:

Method reference invocation 'ServiceType::getId' may produce '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?

How can I get rid of this warning?

UPD: Sticked with:

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. And when that one is null, that gives an 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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