This is a follow up question from :: (double colon) operator in Java 8 in which Java allows you to refer to methods using ::
operator.
Is it possible to provide some custom Functional Interface that I create and use it with ::
operator? And how to do it?
Here you go
How to provide custom functional interface implementation to use
::
operatorPhase 1: Create a custom functional interface
I have created my own
FunctionalInterface
namedMyCustomInterface
and in Java 8 you have to declare the interface to be functional interface using@FunctionalInterface
annotation. Now it has a single method takingint
as param and returningint
.Phase 2: Create some methods confirming to that signature
Created two methods
customMethod1
andcustomMethod2
which confirm to the signature of that custom interface.Phase 3: Create a method that takes Functional Interface (
MyCustomInterface
) as argumentmethod
takesMyCustomInterface
in the argument.And you are ready to go.
Phase 4: Use
In the main I have used the
method
and passed it the implementation of my custom methods.“Is it possible to provide some custom Functional Interface that I create and use it with
::
operator? And how to do it?”It is possible and it’s as easy as you could imagine: just create an interface with exactly one method. You don’t even need the
@FunctionalInterface
annotation; this annotation just documents your intention and helps detecting errors at compile time similar to@Override
.So maybe you already have created such interfaces in your pre-Java 8 projects…