classlib: add methods to java.util.Objects

This commit is contained in:
Alexey Andreev 2022-05-08 17:42:26 +03:00
parent a9035a25f0
commit 500d72d596

View File

@ -15,6 +15,7 @@
*/ */
package org.teavm.classlib.java.util; package org.teavm.classlib.java.util;
import java.util.function.Supplier;
import org.teavm.classlib.java.lang.TObject; import org.teavm.classlib.java.lang.TObject;
public final class TObjects extends TObject { public final class TObjects extends TObject {
@ -52,6 +53,25 @@ public final class TObjects extends TObject {
return obj; return obj;
} }
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
if (obj == null) {
throw new NullPointerException(messageSupplier.get());
}
return obj;
}
public static <T> T requireNonNullElse(T obj, T defaultObj) {
return obj != null ? obj : requireNonNull(defaultObj);
}
public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) {
return obj != null ? obj : requireNonNull(supplier.get());
}
public static boolean isNull(Object obj) {
return obj == null;
}
public static boolean nonNull(Object obj) { public static boolean nonNull(Object obj) {
return obj != null; return obj != null;
} }
@ -103,4 +123,25 @@ public final class TObjects extends TObject {
public static int hash(Object... values) { public static int hash(Object... values) {
return TArrays.hashCode(values); return TArrays.hashCode(values);
} }
public static int checkIndex(int index, int length) {
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException();
}
return index;
}
public static int checkFromToIndex(int fromIndex, int toIndex, int length) {
if (fromIndex < 0 || fromIndex > toIndex || toIndex > length) {
throw new IndexOutOfBoundsException();
}
return fromIndex;
}
public static int checkFromIndexSize(int fromIndex, int size, int length) {
if (fromIndex < 0 || size < 0 || fromIndex + size > length) {
throw new IndexOutOfBoundsException();
}
return fromIndex;
}
} }