在单个函数中重构java,检查不同数据类型的null
我有很多这样的陈述在单个函数中重构java,检查不同数据类型的null,java,Java,我有很多这样的陈述 boolean isIdEqual = (retrievedEdition.getId() == null && edition.getId() == null) || (retrievedEdition.getId() !=null && edition.getId() != null && retrievedEdition.getId().equals(edition.getId())); 这是用于单元测试的。我正在检查
boolean isIdEqual = (retrievedEdition.getId() == null && edition.getId() == null) || (retrievedEdition.getId() !=null && edition.getId() != null && retrievedEdition.getId().equals(edition.getId()));
这是用于单元测试的。我正在检查几种数据类型的null,比如long、int、Integer和String。
我想要一个函数,可以检查两种数据类型,缩短上面的语句并重构代码 无法
对象。相等(对象,对象)
为您计算
Objects.equals(retrievedEdition.getId(), edition.getId());
从:
如果参数彼此相等,则返回true,否则返回false。因此,如果两个参数都为null,则返回true;如果只有一个参数为null,则返回false。否则,通过使用第一个参数的equals方法确定相等性
Objects
类是在Java 7中引入的,如果您使用的是早期版本,则实现如下所示:
/**
* Returns {@code true} if the arguments are equal to each other
* and {@code false} otherwise.
* Consequently, if both arguments are {@code null}, {@code true}
* is returned and if exactly one argument is {@code null}, {@code
* false} is returned. Otherwise, equality is determined by using
* the {@link Object#equals equals} method of the first
* argument.
*
* @param a an object
* @param b an object to be compared with {@code a} for equality
* @return {@code true} if the arguments are equal to each other
* and {@code false} otherwise
* @see Object#equals(Object)
*/
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
可以使用三元表达式简化该代码:
boolean isIdEqual = retrievedEdition.getId() != null ? retrievedEdition.getId().equals(edition.getId()) : edition.getId() == null;
这里有很多东西 我正在检查几种数据类型的空值,如long、int、Integer、String。-->对于原语,不能检查
null
其次,
我想要一个可以检查两种数据类型的函数
像这样的东西可能有用
boolean checkForNull(Object o1, Object o2){
{
//check here
}
您可以在代码中使用它,如下所示
boolean isIdEqual = Validator.checkEqualsOrNull(retrievedEdition.getId() ,
edition.getId());
这是一个通用函数,可以用于所有检查。您有什么问题吗?我使用的是较低级别的javaversion@ahmedragia,我还为早期版本添加了一个实现示例。那么如何检查布尔值是否为空?@ahmedragia布尔值不能为空,由于原语不能为null。那么布尔值呢?我得到了与for return null for boolean不兼容的类型抱歉,我更改了它(return null->return false)是一个键入错误。对于将布尔值转换为等效布尔包装的自动装箱取消装箱功能的布尔值,也可以调用它。
boolean isIdEqual = Validator.checkEqualsOrNull(retrievedEdition.getId() ,
edition.getId());