javajava-8argument-passingmethod-reference

Is it possible to pass argument via method reference?


I have the following code line:

MyClass{
    Runnable job; 
    ...    
}

and inside one of the method:

this.job = myImporter::importProducts;

Now importProducts is method without arguments:

public void importProducts() {
        ...
}

But I need to add argument to this method now.

After adding new argument, line:

this.job = myImporter::importProducts;

became broken.

Is it possible to fix it?


Solution

  • It's not possible to "bind" and argument directly to the method reference. In this case you can easily use lambda:

    this.job = () -> myImporter.importProducts(myNewArgument);
    

    Alternatively if it fits your situation consider leaving the zero-arguments importProducts method which just calls the one-argument importProducts with proper argument value:

    public void importProducts() {
        importProducts(myNewArgument);
    }
    
    private void importProducts(Type arg) {
        ...
    }
    

    This way your method reference will work as before.