为什么IntelliJ告诉我我的类永远不会返回null?

问题描述 投票:1回答:2
private void addCompoundsFrom(Verse verse) {
    Optional<List<Compound>> compounds = Optional.of(verse.getCompounds());
    if (compounds.isPresent()) {
        for (Compound compound : compounds.get()) {
            addCompoundsFrom(compound);
        }
    }
}

IntelliJ检查器告诉我if语句始终为true。怎么知道呢?这是Compounds类:

public class Compounds extends PositionalIds {

    @XmlElement(name = "verse")
    private List<Verse> verses;

    public List<Verse> getVerses() {
        return verses;
    }
}


@XmlTransient
public abstract class PositionalIds {

    @XmlAttribute(name = "start")
    private String startId;

    @XmlAttribute(name = "end")
    private String endId;

    public String getStartId() {
        return startId;
    }

    public String getEndId() {
        return endId;
    }
}

和诗班:

public class Verse extends PositionalIds {

    @XmlElement(name = "compound")
    private List<Compound> compounds;

    @XmlAttribute(name = "notation")
    private String notation;

    public List<Compound> getCompounds() {
        return compounds;
    }

    public String getNotation() {
        return notation;
    }
}

如果我停止使用Optional来包装verse.getCompounds()结果而只是进行空检查,则检查消息就会消失。

我正在使用Java 8。

java intellij-idea
2个回答
6
投票

Optional类有两种方法:

  • Optional.of - >如果参数是null则抛出异常
  • Optional.ofNullable - >如果参数是null,则创建一个空的可选项

因此,如果您的方法返回null,则of()方法将抛出异常并且空可选将永远不会到达您的if语句


2
投票

Optional.of(verse.getCompounds());返回包含有效值的Optional

随后的isPresent检查将始终为真,因为Optional compounds永远不会有值,因为您只需将其设置为上面一行的有效值。

© www.soinside.com 2019 - 2024. All rights reserved.