What is the Lambda syntax to pass and invoke a method reference?
Scenario: Building objects (radio buttons) based on values in an Enum.
I pass a Collection of the enum’s values. I want the other method (a constructor) to call a method on each of those enum values. That method call determines the displayed label for each radio button.
But the name of that method varies by each particular Enum class. Some enums have a getTitle
method, another might have a method named getDescription
or getCaption
, and yet another might have getLocalizedVariationOfTitle
. How do I let each calling programmer pass their particular method to be invoked?
Collection<SomeEnum> enumValues = Arrays.asList( SomeEnum.values() );
x = new EnumRadioButtons( enumValues , ??methodReferenceToGetTitle?? );
The syntax of passing, and invoking, ??methodReferenceToGetTitle??
eludes me. Constructor looks like this:
public EnumRadioButtons ( Collection<?> options , ??methodReferenceToGetTitle?? ) {
…
for ( Object option : options ) {
this.setTitleOfEachOption( option , ??methodReferenceToGetTitle?? );
}
}
When the method reference is dereferenced, the code effectively becomes:
this.setTitleOfEachOption( option , option.getTitle() ); // Pass the radio button item, and its label text.
or:
this.setTitleOfEachOption( option , option.getDescription() );
or:
this.setTitleOfEachOption( option , option.getSomeLocalizedVariationOfTitle() );
I tried passing MyEnum::getTitle
for an enum named MyEnum
that does indeed have a method getTitle()
. But I get compiler errors.
I have a hunch this answer by might be use of a Supplier
:
public EnumRadioButtons ( Collection<?> options , java.util.function.Supplier<String> supplierOfTitle ) {
super( caption , options );
for ( Object option : options ) {
this.setTitleOfEachOption( option , supplierOfTitle.get() );
}
}
As a workaround, I could require each Enum to implement an interface of TitleGetable
such as:
public interface TitleGetable
{
public String getTitle ();
}
But having all the calling programmers carry and explicitly implement this extra interface seems silly. Given this is a single method returning just a String, it seems like it is begging for a simple Lambda syntax.