Java 对 Javabean 嵌套属性进行 null 检查

标签 java nullpointerexception

我正在使用 BigDecimal 计算,并且读到检查 null 比用 try catch 包围更好。例如:

private BigDecimal computeSpringRateBoltWasher() {
    if (boltWasher.getMaterial().getElastic_modulus() != null) {
      BigDecimal term1 = boltWasher.getMaterial().getElastic_modulus().multiply(BigDecimal.TEN);
        // other equations 
      return results;
    }
   return null;
}

但这里我得到一个 nullPointerException,因为 bolt 垫圈的 Material 为 null。如何干净地检查 Material 和弹性模量的空值?

它可以归结为这样的事情吗?我需要在此方法中检查一些其他属性,这可能会变得困惑。

private BigDecimal computeSpringRateBoltWasher() {
    if (boltWasher.getMaterial() != null) {
       if (boltWasher.getMaterial().getElastic_modulus() != null) {

最佳答案

简化您的代码(将boltWasher.getMaterial() 提取到一个新变量,使您的代码更具可读性)。 如果您正在编写 API 或应用程序提供验证,Apache commons 会派上用场。我会这样做,请参阅代码中的注释:

import org.apache.commons.lang3.Validate;

import java.math.BigDecimal;

/**
 * Any
 */
 public class Any {

    private BigDecimal anything;

    public void setAnything(BigDecimal anything){
            this.anything = anything;
    }

    /**
     * computeSpringRateBoltWasher. Explain what this method is intended to do.
     *
     * @return the result of the calculation
     * @throws NullPointerException when anything is null, explain what other fields could cause an exception
     */
    public BigDecimal computeSpringRateBoltWasher() {
            Validate.notNull(this.anything, "Anything must not be null");
            //Validate.notNull(somethingElse, "Something else must not be null");
            BigDecimal term1 = this.anything.multiply(BigDecimal.TEN);
            //Do more things with term1 and return a result
            return term1;
    }


    public static void main(String[] args){

            Any any = new Any();
            any.setAnything(new BigDecimal(10));
            BigDecimal result = any.computeSpringRateBoltWasher();
            System.out.println(result);


            any.setAnything(null);
            result = any.computeSpringRateBoltWasher();
            System.out.println(result);

    }
 }

这将产生以下输出(您决定捕获运行时异常)

Exception in thread "main" java.lang.NullPointerException: Anything must not be null
    at org.apache.commons.lang3.Validate.notNull(Validate.java:222)
    at Any.computeSpringRateBoltWasher(Any.java:20)
    at Any.main(Any.java:36)

关于Java 对 Javabean 嵌套属性进行 null 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31412103/

相关文章:

java - 什么是NullPointerException,我该如何解决?

java - Android 在同一布局 xml 上有一个表格和按钮

java - 带有警报管理器的 Android 上下文

java - clientResponse.getEntity(String.class) 返回 HTML 而不是 JSON

java - 数组相交方法中的空指针(java)

java - 空指针异常, "Attempt to read from field on a null object reference"

android - Android中无法启动Activity组件信息和Java空指针异常

java - 反射 - 将接口(interface)实现为参数的类

java.util.NoSuchElementException 错误

java - NullPointerException 仅适用于某些设备上的动画