Java 7中新增了 Objects工具类,该类提供了对象操作常用的方法,这些方法大多是能防NPE异常的。
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));//会调用具体类重写的equals方法,如果没用重写则调用Object的equals方法比较地址;
}
public static String toString(Object o, String nullDefault) {
return (o != null) ? o.toString() : nullDefault;
}
public static String toString(Object o) {
return String.valueOf(o);
}
/**
* Returns {@code true} if the provided reference is {@code null} otherwise
* returns {@code false}.
*
* @apiNote This method exists to be used as a
* {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
*
* @param obj a reference to be checked against {@code null}
* @return {@code true} if the provided reference is {@code null} otherwise
* {@code false}
*
* @see java.util.function.Predicate
* @since 1.8
*/
public static boolean isNull(Object obj) {
return obj == null;
}