Java 8: method reference to a static method in a non-static way

  • A+

I'm studying the new Stream API for the OCP exam and I found something that I don't really understand. Here's my code:

void methodOne() {, 2); // This works fine.     Stream.of(1,2,3)         .sorted(this::compare); // Compilation error. }  static Integer compare(Integer s1, Integer s2) {     return 0; } 

Here I have a static method called compare and a non-static one called compare. If I call the compare method from the non-static method I get a compiler warning:

The method compare(Integer, Integer) from the type TestStream should be accessed in a static way

If I instead use a method reference to that same method in my stream, that compiler warning becomes a compiler error with the same message.

I know why I get the warning but I don't get why this warning becomes a compilation error if I use a method reference. I didn't find anything online either. Can someone explain it to me?


Accessing a static method via a reference was seen as a design error to this day AFAIK. You can even do:

YourClass c = null; (...) 

And that would work just fine (with a warning though).

When java-8 features where designed this was corrected, so the only way to access a static method (for a method reference) is via the class itself:



:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: