gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:20:39 27 4
gpt4 key购买 nike

我正在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com