java - 检查链 "get"调用 null

标签 java null nullpointerexception

假设我想执行以下命令:

house.getFloor(0).getWall(WEST).getDoor().getDoorknob();

为避免 NullPointerException,如果出现以下情况,我必须执行以下操作:

if (house != null && house.getFloor(0) && house.getFloor(0).getWall(WEST) != null
  && house.getFloor(0).getWall(WEST).getDoor() != null) ...

有没有一种方法或已经存在的 Utils 类可以更优雅地做到这一点,让我们说如下?

checkForNull(house.getFloor(0).getWall(WEST).getDoor().getDoorknob());

最佳答案

如果您无法避免违反所选答案中所述的得墨忒耳法则 (LoD),并使用 Java 8介绍Optional ,这可能是处理诸如您的获取链中的空值的最佳做法。

Optional type 将使您能够连续管道多个映射操作(包含 get 调用)。在后台自动处理空检查。

例如,当对象没有被初始化时,不会产生 print() 并且不会抛出异常。我们在引擎盖下轻轻地处理这一切。初始化对象时,将进行打印。

System.out.println("----- Not Initialized! -----");

Optional.ofNullable(new Outer())
        .map(out -> out.getNested())
        .map(nest -> nest.getInner())
        .map(in -> in.getFoo())
        .ifPresent(foo -> System.out.println("foo: " + foo)); //no print

System.out.println("----- Let's Initialize! -----");

Optional.ofNullable(new OuterInit())
        .map(out -> out.getNestedInit())
        .map(nest -> nest.getInnerInit())
        .map(in -> in.getFoo())
        .ifPresent(foo -> System.out.println("foo: " + foo)); //will print!

class Outer {
    Nested nested;
    Nested getNested() {
        return nested;
    }
}
class Nested {
    Inner inner;
    Inner getInner() {
        return inner;
    }
}
class Inner {
    String foo = "yeah!";
    String getFoo() {
        return foo;
    }
}

class OuterInit {
    NestedInit nested = new NestedInit();
    NestedInit getNestedInit() {
        return nested;
    }
}
class NestedInit {
    InnerInit inner = new InnerInit();
    InnerInit getInnerInit() {
        return inner;
    }
}
class InnerInit {
    String foo = "yeah!";
    String getFoo() {
        return foo;
    }
}

所以,使用你的 getters 链,它看起来像这样:

Optional.ofNullable(house)
        .map(house -> house.getFloor(0))
        .map(floorZero -> floorZero.getWall(WEST))
        .map(wallWest -> wallWest.getDoor())
        .map(door -> wallWest.getDoor())

它的返回将类似于 Optional<Door>这将使您的工作更加安全,而不必担心空异常。

关于java - 检查链 "get"调用 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3458451/

相关文章:

java - Android SharedPreferences 似乎不起作用

Java 方法错误地在 kotlin 中自动重载

sql - Psql not null 错误但值不为空

android - 在另一个类的 ProgressBar 上设置进度

java - 将 Date 对象转换为日历对象

java - 如何创建可扩展列表?

java - Eclipse错误: Could not find or load main class

MYSQL 在 'is null'后使用 'on',在 'where'语句中使用 'left join'

powershell - 这两个 $null 值为什么以及如何不同?

java - 空指针异常 jnlp.FileSaveService