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。
Optional
类有两种方法:
Optional.of
- >如果参数是null
则抛出异常Optional.ofNullable
- >如果参数是null
,则创建一个空的可选项因此,如果您的方法返回null,则of()
方法将抛出异常并且空可选将永远不会到达您的if
语句
Optional.of(verse.getCompounds());
返回包含有效值的Optional
。
随后的isPresent
检查将始终为真,因为Optional
compounds
永远不会有值,因为您只需将其设置为上面一行的有效值。