java - eclipse 自动生成 !=null 递归调用

标签 java eclipse templates eclipse-jdt

给定一个 java 代码,例如:

Something v = a.getB().getC().getD().getE();

Eclipse(模板或外部插件)中是否有生成安全链调用的方法:

if(a!=null && 
   a.getB()!=null &&
   a.getB().getC()!=null &&
   a.getB().getC().getD()!=null &&        
   a.getB().getC().getD().getE()!=null){
          Something v = a.getB().getC().getD().getE(); 
   }        

最佳答案

您是否考虑过 try{} catch(NullPointerException e){} block ?它可能感觉不那么优雅,但如果任何方法调用失败,它会停止你的代码,因为前一个方法返回 null,如果它是 null,它会让你有机会给出默认值。

另一种选择是这样的:

Something v = /*Default Value*/ // Will be overwritten if subsequent methods succeed.
Object temp = a.getB(); // Use whatever Object type getB() returns.
if(temp != null){
    temp = temp.getC(); 
    /* If getC() returns a different type of object, 
     * either use a different variable or make the temp variable even broader 
     * (such as the generic Object type) */
    if(temp != null){
        temp = temp.getD();
        if(temp != null){
            temp = temp.getE();
            if(temp != null)
                v = temp; 
                /* If all previous calls returned something substantial, 
                 * v will be something useful */
            }//if(getE() != null)
        }//if(getD() != null)
    }//if(getC() != null)
}//if(getB() != null)

如果需要,您可以通过不嵌套 if 语句来使用 CPU 效率稍低但更易于阅读的版本。如果所有 if 语句都在彼此之后执行,单个 null 将阻止所有下一个语句的执行,尽管它的值仍然会每次都被检查。

至于生成这些语句,我不太确定。这实际上取决于您可以提前多长时间预测从以前的方法调用返回的 Object 中可以使用哪些新方法。如果您的目标是自动生成代码,我的第一个建议可能会更好:try-catch

关于java - eclipse 自动生成 !=null 递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17967494/

相关文章:

c++ - 专用结构/类中未识别的数据成员

c++ - 如何返回嵌套在其他包中的模板包?

c++ - 使用类模板需要参数列表

java - 使用 jboss 进行 Eclipse 远程调试

java - 使用 Spring 从命令行运行 Java cron 时出错

java - 计算 ZIP 目录中的文件 - JAVA、Android

java - 是否有用于对文件夹和子文件夹中的所有 jar 进行签名的工具?

eclipse - 在 $PATH 中找不到程序 'nvcc'

java - 使用 jsoup 获取链接并将其重定向到最后带有 ?token= 的链接

java - Java 中的矩阵操作 OOP