I've recently encountered another NullPointerException
in Java. It took me quite some time to figure it out, but in the end I found the problem.
Here's the thing: it's a Java 8 method reference that is causing the exception.
When I convert that exact same piece of code to a lambda abstraction, everything works just fine.
I've managed to break it down to this SSCCE:
import java.util.function.Consumer;
public class Main{
public static void main(String[] args) {
Bar bar = new Bar(System.out::println);
Baz baz = new Baz(System.out::println);
bar.fooYou();
baz.fooYou();
}
}
abstract class Foo {
Consumer<String> fooConsumer;
Foo() {
fooConsumer = createConsumer();
}
void fooYou() {
fooConsumer.accept("foo yay!");
}
abstract Consumer<String> createConsumer();
}
class Bar extends Foo {
final Consumer<String> barConsumer;
Bar(Consumer<String> c) {
barConsumer = c;
}
@Override
Consumer<String> createConsumer() {
return t -> barConsumer.accept(t);
}
}
class Baz extends Foo {
final Consumer<String> bazConsumer;
Baz(Consumer<String> c) {
bazConsumer = c;
}
@Override
Consumer<String> createConsumer() {
return bazConsumer::accept;
}
}
This results in a "foo yay!", followed by the exception.
That means the class Bar works just fine. Baz however fails.
I've read but not fully understood the specs at Run-Time Evaluation of Method References and I feel like the solution should be somewhere in there.
Does anyone know what is the difference between the lambda and the method reference regarding null values etc?
I hope there's some expert out there who can help me. The bug was too annoying not to find out the exact behaviour of Java 8. Thank you in advance!
PS: After reading the specs I actually thought that none of Bar, Baz should work. So why does one..?