gstackoverflow
gstackoverflow

Reputation: 37034

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?

Upvotes: 2

Views: 105

Answers (1)

Tagir Valeev
Tagir Valeev

Reputation: 100169

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.

Upvotes: 2

Related Questions