【问题标题】:TryFind method in Guava throw NullPointerExceptionGuava 中的 TryFind 方法抛出 NullPointerException
【发布时间】:2016-10-04 11:24:01
【问题描述】:

我在运行我的 web 应用程序时得到一个 NullPointerException,我保存了一个日志并再次启动服务器,这个错误不再出现,但我希望 NullPointer 的保护方法永远不会出现。我确定这条线是造成这个错误的原因

Vehicle pVehicle =
        Iterables.tryFind(aFactory.getVehicle(), new Predicate<Vehicle>() {
            @Override
            public boolean apply(Vehicle vehicle) {
                return vehicle.getVehicleBrand().equals(aVehicle.getVehicleBrand());
            }
        }).orNull();

但这不是我的代码,我不知道是哪一部分导致了这个错误> 请问,这个 NullPointer 可以出现哪个元素以及如何保护这个代码

【问题讨论】:

标签: java nullpointerexception guava


【解决方案1】:

检查以下陈述:

  • aFactory - 因为getVehicle() 调用。
  • aFactory.getVehicle() - 因为 Iterables.tryFind 需要一个非空的 Iterable
  • vehicle - 因为getVehicleBrand() 调用
  • aVehicle - 因为getVehicleBrand() 调用
  • vehicle.getVehicleBrand() - 因为.equals() 调用

如果其中任何一个为空,则会导致NullPointerException

【讨论】:

  • 它必须是 getVehicleBrand() ,我保护了这个元素
【解决方案2】:

可以生成空指针:

aFactory.getVehicle() : if aFactory is null
vehicle.getVehicleBrand() : if vehicle is null
aVehicle.getVehicleBrand() : if aVehicle is null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    相关资源
    最近更新 更多