I was trying to create a method reference to an arbitrary object, so I defined the following types:
interface I {
boolean get(Impl impl);
}
static class Impl {
public boolean get() {
return true;
}
}
Then I declared the method reference, like below:
I i = Impl::get;
When I call:
i.get(null);
I get a NullPointerException:
Exception in thread "main" java.lang.NullPointerException
Can someone explain why this happens even though the Impl
reference is not used anywhere?
The NullPointerException can be avoided using checks and preventive techniques like the following: Making sure an object is initialized properly by adding a null check before referencing its methods or properties. Using Apache Commons StringUtils for String operations e.g. using StringUtils.
Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.
NullPointerException is an unchecked exception and extends RuntimeException class. Hence there is no compulsion for the programmer to catch it.
Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem. The program explicitly throws a NullPointerException to signal an error condition.
I think you misunderstood the meaning of this line:
I i = Impl::get;
I
is a functional interface that represents a method that takes an Impl
and returns a boolean
, whereas get
is a method that takes no parameters and returns a boolean
. How does this conversion work? Well, the compiler realises that get
is an instance method, and to call it you must need a Impl
object. Isn't that just like a function having a parameter before it is called?
So the compiler can happily infer that you meant:
I i = impl -> impl.get();
Now the cause of the NPE should be clear.
In general, all instance methods can be thought of as static methods that take one extra parameter, of type T
where T
is the declaring type of that instance method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With