231. Optional and null references

It is possible to take advantage of orElse(null) by using a method that accepts the null references in certain situations.

A candidate for this scenario is Method.invoke() from the Java Reflection API (see Chapter 7, Java Reflection Classes, Interfaces, Constructors, Methods, and Fields).

The first argument of Method.invoke() represents the object instance on which this particular method is to be invoked. If the method is static, the first argument should be null, and so there is no need to have an instance of the object.

Let's assume that we have a class named Book and the helper method listed as follows.

This method returns an empty Optional class (if the given method is static) or an Optional class containing an instance of Book (if the given method is non-static):

private static Optional<Book> fetchBookInstance(Method method) {

if (Modifier.isStatic(method.getModifiers())) {
return Optional.empty();
}

return Optional.of(new Book());
}

Calling this method is pretty simple:

Method method = Book.class.getDeclaredMethod(...);

Optional<Book> bookInstance = fetchBookInstance(method);

Furthermore, if Optional is empty (meaning that the method is static), we need to pass null to Method.invoke(); otherwise, we pass the Book instance. A clumsy solution may rely on the isPresent()-get() pair, as follows:

// Avoid
if (bookInstance.isPresent()) {
method.invoke(bookInstance.get());
} else {
method.invoke(null);
}

But this is a perfect fit for Optional.orElse(null). The following code reduces the solution to a single line of code:

// Prefer
method.invoke(bookInstance.orElse(null));
As a rule of thumb, we should use orElse(null) only when we have Optional and we need a null reference. Otherwise, avoid orElse(null).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset