Nullcheck method using java8 method?

Thanks to rich profiling, our Java code is cluttered with null outputs of the object method.

Looks like this

namedObject == null ? "?" : namedObject.getName() 

Is it possible to write a static method for this? (for example, as follows):

 Util.nvl( namedObject, NamedObject::getName, "?" ) 

What will = Util.nvl look like? I experimented a bit on google search but did not give a result.

This does not work:

 public static <T> T nvl(T value, Function<T, ?> method, T nullSubstition) { return value == null ? nullSubstition : (T) method.apply(value); } 

The compiler tells me: the non-static getName () method cannot reference a static context

+6
source share
2 answers

Your signature may not be correct. You want your method to take NamedObject as the first argument (so T is NamedObject) and return a string (so now T is a string).

You need two types of type type:

 public class Utils { public static <O, T> T nvl(O value, Function<O, T> method, T nullSubstition) { return value == null ? nullSubstition : method.apply(value); } static class NamedObject { String getName() { return "foo"; } } public static void main(String[] args) { NamedObject foo = null; String name = Utils.nvl(foo, NamedObject::getName, "bar"); System.out.println("name = " + name); // name = bar foo = new NamedObject(); name = Utils.nvl(foo, NamedObject::getName, "bar"); System.out.println("name = " + name); // name = foo } } 

An even better signature providing greater flexibility would be

 public static <O, T> T nvl(O value, Function<? super O, ? extends T> method, T nullSubstition) { return value == null ? nullSubstition : method.apply(value); } 
+8
source

Your general methods methods are not defined correctly. You are trying to create a method that receives an object of a certain type ( T , for the sake or NamedObject in this example) and uses a method that returns an object of another type ( S , for the sake or String argument in this example) or the default value S if passed null object:

 public static <T, S> S nvl(T value, Function<T, S> method, S nullSubstition) { return value == null ? nullSubstition : (S) method.apply(value); } 

Please note that Java 8 Optional may allow you to write this in a more elegant way (although elegance is somewhat in the eyes of the beholder):

 public static <T, S> S nvl(T value, Function<T, S> method, S nullSubstition) { return Optional.ofNullable(value).map(method).orElse(nullSubstition); } 
+5
source

Source: https://habr.com/ru/post/1013505/


All Articles