Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException when calling a method reference to an arbitrary object with null argument [duplicate]

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?

like image 549
mrboieng Avatar asked Nov 04 '19 16:11

mrboieng


People also ask

How do I fix NullPointerException?

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.

Which of the following will help us to avoid NullPointerException in Java 8?

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.

Is NullPointerException checked or unchecked?

NullPointerException is an unchecked exception and extends RuntimeException class. Hence there is no compulsion for the programmer to catch it.

Can you catch a NullPointerException?

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.


1 Answers

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.

like image 134
Sweeper Avatar answered Oct 13 '22 13:10

Sweeper