NameCreator::createName
implies that either the method is static (kind #1 in the table below), or that the functional interface target also takes an instance of the class (kind #3, for example
BiFunction<NameCreator, String, String>
). Your methods are not static, and so presumably your target does not take an instance, which is why you get the "Cannot resolve method" error. You probably want to use the method reference on an instance (kind #2). From within the class, you can use:
Function<String, String> func = this::createName
From outside the class you can use:
NameCreator creator = new NameCreator();
Function<String, String> func = creator::createName;
As to whether the one- or two-parameter version is used, it depends on what functional interface is being targeted. The above will use your first method, because Function<String, String>
takes a String and returns a String. The following functional interface, as an example, would use your second method:
NameCreator creator = new NameCreator();
BiFunction<String, String, String> func = creator::createName;
See: Function
, BiFunction
, and the whole java.util.function
package
You may also be interested in the Java tutorial on method references, specifically this part:
There are four kinds of method references:
Kind | Example
==============================================================================================
Reference to a static method | ContainingClass::staticMethodName
-------------------------------------------------------+--------------------------------------
Reference to an instance method of a particular object | containingObject::instanceMethodName
-------------------------------------------------------+--------------------------------------
Reference to an instance method of an arbitrary object | ContainingType::methodName
of a particular type |
-------------------------------------------------------+--------------------------------------
Reference to a constructor | ClassName::new
==============================================================================================