IntelliJ IDEA 2016.3 Help

Extract Functional Parameter

When you perform the Extract Functional Parameter refactoring, IntelliJ IDEA:

  1. Analyzes the selected code fragment to find out what the method signature would be if you extracted this fragment into a new separate method.
  2. Finds all functional interfaces with this method signature and suggests that you select one of them. (Only the interfaces marked with @FunctionalInterface or ones belonging to well-known libraries such as Guava, Apache Collections, etc. are suggested.)
  3. Wraps the code fragment with an anonymous class based on the selected interface and uses this anonymous class as a parameter.
  4. Where appropriate, makes related code adjustments.

Example

BeforeAfter
@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 interface Person. This anonymous class is passed as a parameter to the call to printHello() within printText().
  • Person is added as a parameter to printHello() and the initially selected code fragment is replaced with the call to the method of the interface (sayHello()).

Performing the Extract Functional Parameter refactoring

  1. Select the code fragment of interest and do one of the following:
    • Press Ctrl+Shift+Alt+P.
    • Select Refactor | Extract | Functional Parameter from the main or the context menu.
    • Select Refactor | Refactor This from the main menu (Ctrl+Shift+Alt+T), and select Functional Parameter.
  2. Select the desired functional interface from the list.
  3. Specify the refactoring options in the Extract Parameter dialog.

See Also

Last modified: 7 December 2016