Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Reference. Cannot make a static reference to the non-static method

Can someone explain to me,
why passing a non-static method-reference to method File::isHidden is ok,
but passing method reference to a non-static method MyCass::mymethod - gives me a "Cannot make a static reference to the non-static method" ?

public static void main(String[] args) {
    File[] files = new File("C:").listFiles(File::isHidden); // OK
    test(MyCass::mymethod); // Cannot make a static reference to the non-static method
}

static interface FunctionalInterface{
    boolean function(String file);
}

class MyCass{
    boolean mymethod(String input){
        return true;
    }
}

// HELPER
public static void test(FunctionalInterface functionalInterface){}
like image 551
Skip Avatar asked Sep 16 '15 21:09

Skip


1 Answers

Method references to non-static methods require an instance to operate on.

In the case of the listFiles method, the argument is a FileFilter with accept(File file). As you operate on an instance (the argument), you can refer to its instance methods:

listFiles(File::isHidden)

which is shorthand for

listFiles(f -> f.isHidden())

Now why can't you use test(MyCass::mymethod)? Because you simply don't have an instance of MyCass to operate on.

You can however create an instance, and then pass a method reference to your instance method:

MyCass myCass = new MyCass(); // the instance
test(myCass::mymethod); // pass a non-static method reference

or

test(new MyCass()::mymethod);

Edit: MyCass would need to be declared static (static class MyCass) in order to be accessible from the main method.

like image 111
Peter Walser Avatar answered Oct 26 '22 11:10

Peter Walser