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

Aurasphere :

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() {
    this.compare(1, 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?

Eugene :

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

YourClass c = null;
c.compare (...)

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:

YourClass::compare

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464713&siteId=1