【问题标题】:How to avoid null in Java method chainJava方法链中如何避免null
【发布时间】:2021-02-03 10:16:37
【问题描述】:

这是我的代码 sn-p。

     String fileName = "";
     FileDTO file = 
     FileService.findById(fileId);
    if(file != null && file.getFileFormate() != null){
        fileName = file.getFileName();
        fileName = "." +file.getFileFormate().getExtension();
    }

在这里我可以看到 Null 指针异常的可能性。如果文件不为空,然后 file.getFileFormate() 不为空,那么我可以调用 file.getFileFormate().getExtension()。所以我必须为它们中的每一个检查 null 。有没有飞的方法来检查它。类似的东西:-

file?.getFileFormate()?.getExtension()

JVM也是从右到左从左到右执行代码吗?

所以我的代码冷如检查:

if(file != null && file.getFileFormate() != null)

or

if(file.getFileFormate() != null  && file != null)

or

if(null != file.getFileFormate()  &&  null != file)

【问题讨论】:

  • 从左到右 & 没有。没有其他办法。你必须把它锁起来
  • Java 没有 ? 运算符,您无法通过这种方式检查 null

标签: java nullpointerexception null-pointer


【解决方案1】:

由于大概FileDTO 是您编写的一个类,您可以像这样简化对空值的检查:

if(file != null){
    fileName = file.getFileName();
    fileName = "." +file.getExtension();
}

然后在FileDTO中添加如下内容:

public String getExtension() {
    String extension = "";
    if (this.getFileFormate() != null) {
        extension = this.getFileFormate().getExtension();
    }
    return extension;
}

这样做的额外好处是不会暴露FileDTO 的内部实现细节。

至于你的其他问题,正如评论已经说过的那样,从左到右,但是some operators have an order of precedence

【讨论】:

    猜你喜欢
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多