Due to rich profiling, our Java code is cluttered with outputs of method results of nullable objects.
It looks like this
namedObject == null ? "?" : namedObject.getName()
is it possible to write a static method for this? (e.g. looking like this):
Util.nvl( namedObject, NamedObject::getName, "?" )
What would = Util.nvl look like? I've experimented a bit an searched google but yielded no 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: non-static method getName() cannot be referenced from a static context
Your signature can't be correct. You want your method to take the NamedObject as first argument (so T is a NamedObject), and to return a String (so now T is String).
You need two generic type parameters:
An even better signature, allowing more flexibility, would be