IntelliJ IDEA 2022.1 Help

Convert anonymous to inner

The Convert Anonymous to Inner refactoring allows you to convert an anonymous class into a named inner class.

  1. Position the caret within the anonymous class to be refactored.

  2. From the main menu, or from the context menu of the selection, select Refactor | Convert Anonymous To Inner.

  3. In the dialog that opens, specify the name for the new inner class and variables that will be used as parameters to the inner class constructor. You can also indicate whether you want to make your class static.

  4. Click OK to create the inner class.

Example

Before

After

public class Class { public Interface method() { final int i = 0; return new Interface() { public int publicMethod() { return i;} }; } }
public class Class { public Interface method() { final int i = 0; return new MyInterfaceClass(i); } } public class MyInterfaceClass implements Interface { private final int i; public MyInterfaceClass(int i) { this.i = i; } public int publicMethod() { return i; } }
Last modified: 10 August 2022