简体   繁体   English

为什么 IntelliJ 告诉我我的类从不返回 null?

[英]Why does IntelliJ tell me that my class never returns null?

private void addCompoundsFrom(Verse verse) {
    Optional<List<Compound>> compounds = Optional.of(verse.getCompounds());
    if (compounds.isPresent()) {
        for (Compound compound : compounds.get()) {
            addCompoundsFrom(compound);
        }
    }
}

The IntelliJ inspector tells me that the if-statement is always true. IntelliJ 检查员告诉我 if 语句始终为真。 How can it know that?它怎么会知道? This is the Compounds class:这是化合物类:

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

And the Verse class:和 Verse 类:

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

If I stop using Optional to wrap the verse.getCompounds() result and instead just do a null check, the inspection message goes away.如果我停止使用Optional来包装verse.getCompounds()结果而只是进行空检查,则检查消息就会消失。

I'm using Java 8.我正在使用 Java 8。

The Optional class has two methods: Optional类有两个方法:

  • Optional.of -> throws exception if the parameter is null Optional.of -> 如果参数为null则抛出异常
  • Optional.ofNullable -> creates an empty optional if the parameter is null Optional.ofNullable -> 如果参数为null则创建一个空的可选

Hence if your method returns null, the of() method will throw an exception and empty optional will never reach your if statement因此,如果您的方法返回 null,则of()方法将抛出异常,而空的可选将永远不会到达您的if语句

Optional.of(verse.getCompounds()); returns an Optional that contains a valid value.返回一个包含有效值的Optional

The isPresent check that follows will always be true because the Optional compounds will never not have a value, since you just set it to a valid value on the line above.随后的isPresent检查将始终为真,因为Optional compounds永远不会没有值,因为您只是在上面的行中将其设置为有效值。

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

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