NPEUtil.java
package com.tradecloud.common.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
public class NPEUtil<T> {
private final Supplier<T> supplier;
private T defaultValue = null;
public NPEUtil(Supplier<T> supplier) {
this.supplier = Optional.ofNullable(supplier).orElse(() -> null);
}
public NPEUtil(Supplier<T> supplier, T defaultValue) {
this.supplier = Optional.ofNullable(supplier).orElse(() -> null);
this.defaultValue = defaultValue;
}
public T get() {
return Optional.ofNullable(supplier.get()).orElse(defaultValue);
}
public T getOrElse(T newDefault) {
return Optional.ofNullable(supplier.get()).orElse(newDefault);
}
public T getIgnoringNPE() {
T evaluated = null;
try {
evaluated = supplier.get();
} catch (NullPointerException ignored) {
//atleast print error so that we can fix the issue
ignored.printStackTrace();
}
return Optional.ofNullable(evaluated).orElse(defaultValue);
}
public T getOrElseIgnoringNPE(T newDefault) {
T evaluated = null;
try {
evaluated = get();
} catch (NullPointerException ignored) {
//atleast print error so that we can fix the issue
ignored.printStackTrace();
}
return Optional.ofNullable(evaluated).orElse(newDefault);
}
public <R> NPEUtil<R> mapWithDefaultIgnoringNPE(Function<T, R> transformer, R newDefault) {
return Optional.ofNullable(getIgnoringNPE()) // here we evaluate by ignoring NPE
.map(transformer)
.map(r -> new NPEUtil<>(() -> r, newDefault))
.orElse(new NPEUtil<>(() -> newDefault));
}
public <R> NPEUtil<R> mapIgnoringNPE(Function<T, R> transformer) {
return mapWithDefaultIgnoringNPE(transformer, null);
}
@SafeVarargs
public final boolean anyNullCatchNPE(T... values) {
List<T> comparison = Arrays.asList(values);
for (T value : comparison) {
try {
if (value != null) {
if (value instanceof Collection && !((Collection<?>) value).isEmpty()
&& comparison.indexOf(value) == comparison.size() - 1) {
return true;
} else if (comparison.indexOf(value) == comparison.size() - 1) {
return true;
}
}
} catch (NullPointerException e) {
return false;
}
}
return false;
}
}