[英]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.