newlogic
newlogic

Reputation: 827

Can method references be used to access static methods?

According to:

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

It looks like its possible, however trying it for real returns a compile error. It makes more sense that it shouldn't be possible as we cannot implement interfaces with static methods.

public class SomeClass {

    static public boolean getB(){
        return false;
    }
}

List<SomeClass> list = new ArrayList<>();       
list.add(new SomeClass());

// below causes compile error, which I expect, however documentation indicates oherwise
list.stream().filter(SomeClass::getB).collect(Collectors.toList());

Here is the compile error:

"Multiple markers at this line - The method getB() from the type SomeClass should be accessed in a static way - The method filter(Predicate) in the type Stream is not applicable for the arguments (SomeClass::getB)"

Upvotes: 1

Views: 153

Answers (1)

JB Nizet
JB Nizet

Reputation: 691805

You can, but the return type and arguments of the method must match the ones of the unique method of the functional interface (Predicate<Something> here).

Assuming your list is a List<Something>, since the predicate is supposed to return a boolean based on a Something as input, your code will compile if your method is defined as

public static boolean getB(Something s)

or

public static boolean getB(Object o)

Upvotes: 6

Related Questions