When you perform the Extract Functional Parameter refactoring, IntelliJ IDEA:
- Analyzes the selected code fragment to find out what the method signature would be if you extracted this fragment into a new separate method.
-
Finds all functional interfaces with this method signature and
suggests that you select one of them.
(Only the interfaces marked with
@FunctionalInterfaceor ones belonging to well-known libraries such as Guava, Apache Collections, etc. are suggested.) - Wraps the code fragment with an anonymous class based on the selected interface and uses this anonymous class as a parameter.
- Where appropriate, makes related code adjustments.
Example
| Before | After |
|---|---|
@FunctionalInterface public interface Person { public void sayHello (String s); } public class Hello { private void printHello () { String s="Hello"; System.out.println(s); } private void printText () { printHello(); } } |
@FunctionalInterface public interface Person { public void sayHello (String s); } public class Hello { private void printHello(Person person) { String s = "Hello"; person.sayHello(s); } private void printText () { printHello(new Person() { public void sayHello(String s) { System.out.println(s); } }); } } |
In this example, the refactoring is performed on System.out.println(s);
within Hello.printHello().
IntelliJ IDEA finds all functional interfaces with the appropriate method signature
((String) -> void) and suggests that you select one of them.
(In this example, the interface Person is selected.)
As a result:
-
The selected fragment (
System.out.println(s);) is wrapped with an anonymous class based on the interfacePerson. This anonymous class is passed as a parameter to the call toprintHello()withinprintText(). -
Personis added as a parameter toprintHello()and the initially selected code fragment is replaced with the call to the method of the interface (sayHello()).
Performing the Extract Functional Parameter refactoring
-
Select the code fragment of interest and do one of the following:
- Press Ctrl+Shift+Alt+P.
- Select from the main or the context menu.
- Select from the main menu (Ctrl+Shift+Alt+T), and select Functional Parameter.
- Select the desired functional interface from the list.
- Specify the refactoring options in the Extract Parameter dialog.
