[英]How to write a generic java method to return value with null check?
我有一些代碼將值從一個 object 復制到另一個。
當我必須檢查 null 值時,我的代碼變得非常冗長且難以閱讀,所以我想要一種方法來獲取 object 的實例並通過 null 檢查返回我需要的值。
有沒有辦法制作這樣的方法?
我的用法類似於以下內容:
objectInstance.setName(methodNullCheck(object.getName()));
objectInstance.setAddress(methodNullCheck(object.getAddress().getFullAddress));
我的意圖是有一個 function 可以對輸入參數進行 NullPointerException 檢查並返回該值(如果存在)。
我該如何編寫這樣的方法?
這是示例代碼:
public <T> T methodNullCheck(T value) {
if (value != null) {
return value;
} else {
throw new IllegalArgumentException("null value");
}
}
我建議在setName()
、 setAddress()
等的輸入參數上使用Lombok和@NonNull
注釋。
您可以創建一個 null 安全 Function
interface NullSafeFunction<T, R> extends Function<T, R> {
default <V> NullSafeFunction<T, V> andThen(Function<? super R, ? extends V> after) {
return (T t) -> Optional.ofNullable(t).map(this::apply).map(after).orElse(null);
}
static <T> NullSafeFunction<T, T> identity() {
return t -> t;
}
}
然后按如下方式使用它
A a1 = new A();
String result1 = NullSafeFunction.<A>identity()
.andThen(A::getB)
.andThen(B::getC)
.andThen(C::getD)
.apply(a1);
System.out.println(result1); //null
A a2 = new A(new B(new C("yes")));
String result2 = NullSafeFunction.<A>identity()
.andThen(A::getB)
.andThen(B::getC)
.andThen(C::getD)
.apply(a2);
System.out.println(result2); //yes
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.