The Change Class Signature refactoring lets you turn a class into a generic and manipulate its type parameters. The refactoring automatically corrects all calls, implementations and overridings of the class.
Example
| Before | After |
|---|---|
// This is the class whose signature will be changed: public class MyClass { // some code here } public class MyOtherClass { // Here are the references to MyClass: MyClass myClass; void myMethod(MyClass myClass) { // some code here } // some code here } // Now we are going to add two formal type parameters // to MyClass. |
// Two formal type parameters have been added: public class MyClass<Param1, Param2> { // some code here } public class MyOtherClass { // The references to MyClass have changed accordingly: MyClass<String, Integer> myClass; void myMethod(MyClass<String, Integer> myClass) { // some code here } // some code here } // When performing the refactoring, String and Integer // were specified as the default values for Param1 and // Param2 respectively. |
Use cases
-
The type parameters can have bounds extending other constructs including other type parameters from
another class.
For instance, the code like
public class ClassA<T, E>can be easily transformed topublic class ClassA<T, E extends T>. However, if the parameter order was initiallypublic class ClassA<E, T>, the Change Class Signature refactoring may be useful for changing the parameter order in the class signature as well as in all its usages. - IntelliJ IDEA can successfully deal with rather complicated cases and can alter parameters and corresponding usages if one parameter depends on another.
Changing a class signature
- In the editor, place the cursor within the name of the class whose signature you want to change.
- Do one of the following:
- Press ⌘F6⌘F6⌥⌘C⌃F6⌃F6.
- Choose Refactor | Change Signature in the main menu.
- Select Refactor | Change Signature from the context menu.
- In the Change Class Signature dialog, use the available
controls to manage the formal type parameters:
- To add a new parameter, click
or press ⌘N⌃N⌘N.
Specify the parameter name and default type in the Name and
the Default Value fields respectively. - To remove a parameter, select the parameter and
click
(⌘⌦⌘⌦⌥⌦). - To move a parameter up or down in the list, select the parameter and then
use
(⌃↑⌃↑⌃⌥↑⌥↑⌥↑)
or
(⌃↓⌃↓⌃⌥↓⌥↓⌥↓).
- To add a new parameter, click
- To perform the refactoring right away, click Refactor.
To see the expected changes and make the necessary adjustments prior to actually performing the refactoring, click Preview.