该类是jdk1.7以后出现的,主要是就是私有构造方法,然后所有方法静态,所以可以直接类名.方法名直接用方法
/**
* This class consists of {@code static} utility methods for operating
* on objects. These utilities include {@code null}-safe or {@code
* null}-tolerant methods for computing the hash code of an object,
* returning a string for an object, and comparing two objects.
*
* @since 1.7
*/
public final class Objects {
......
}
主要的方法有
//比较方法,同一对象直接返回true,不同对象比较值,值相同返回true
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
//
public static boolean deepEquals(Object a, Object b) {
if (a == b)
return true;
else if (a == null || b == null)
return false;
else
return Arrays.deepEquals0(a, b);
}
//对象不为null返回hashcode,为null返回0
public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}
//
public static int hash(Object... values) {
return Arrays.hashCode(values);
}
//
public static String toString(Object o) {
return String.valueOf(o);
}
//不为空返回,toString,为null返回默认值
public static String toString(Object o, String nullDefault) {
return (o != null) ? o.toString() : nullDefault;
}
//
public static <T> int compare(T a, T b, Comparator<? super T> c) {
return (a == b) ? 0 : c.compare(a, b);
}
//
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
//
public static <T> T requireNonNull(T obj, String message) {
if (obj == null)
throw new NullPointerException(message);
return obj;
}
// 为null
public static boolean isNull(Object obj) {
return obj == null;
}
// 不为 null
public static boolean nonNull(Object obj) {
return obj != null;
}
//
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
if (obj == null)
throw new NullPointerException(messageSupplier.get());
return obj;
}