[英]How to write a generic java method to return value with null check?
I have some code which copies values from one object to another.我有一些代码将值从一个 object 复制到另一个。
When I have to null check values my code becomes very lengthy and harder to read, so I want a method that gets the instance of the object and returnd the value I need with a null check.当我必须检查 null 值时,我的代码变得非常冗长且难以阅读,所以我想要一种方法来获取 object 的实例并通过 null 检查返回我需要的值。
Is there a way to make such a method?有没有办法制作这样的方法?
My usages are similar to the following:我的用法类似于以下内容:
objectInstance.setName(methodNullCheck(object.getName()));
objectInstance.setAddress(methodNullCheck(object.getAddress().getFullAddress));
My intention is to have a function that could have a NullPointerException check on the input parameter and return the value if it exists.我的意图是有一个 function 可以对输入参数进行 NullPointerException 检查并返回该值(如果存在)。
How do I write such a method?我该如何编写这样的方法?
Here is example code:这是示例代码:
public <T> T methodNullCheck(T value) {
if (value != null) {
return value;
} else {
throw new IllegalArgumentException("null value");
}
}
I would suggest to use Lombok and @NonNull
annotation on input parameters of setName()
, setAddress()
, etc.我建议在
setName()
、 setAddress()
等的输入参数上使用Lombok和@NonNull
注释。
you can create a null safe Function您可以创建一个 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;
}
}
and then use it as follows然后按如下方式使用它
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.