Convert to Instance Method
Convert to Instance Method refactoring lets you convert a static method to a non-static, class instance method, with a class being the type parameter of the initial method.
In the editor, place the caret at the declaration or usage of a method that you want to refactor. The method should be
static
and the types of its parameters should be the classes from the project. Also note that you cannot use such parameters types asString
.Go to
.You can also use a context menu to access this refactoring.
In the dialog that opens, select the class you want the method to belong to after the conversion. All the usages of this class inside the method are replaced with this.
If you need, change the visibility scope of the converted method.
Preview and apply changes.
Example
Consider classes MyClass
, ClassB
and ClassB
residing in the same package.
As a result, MyClass
and ClassB
become converted.
Before | After |
---|---|
public class MyClass {
ClassA classA = new ClassA();
ClassB classB = new ClassB();
static public void greatMethod(ClassA classA, ClassB classB){
System.out.println("classA = " + classA);
System.out.println("classB = " + classB);
}
public void myMethod(){
MyClass.greatMethod(classA, classB);
}
}
|
public class MyClass {
ClassA classA = new ClassA();
ClassB classB = new ClassB();
public void myMethod(){
classB.greatMethod(classA);
}
}
public class ClassB {
public void greatMethod(ClassA classA) {
System.out.println("classA = " + classA);
System.out.println("classB = " + this);
}
}
|
Convert to instance method dialog
This dialog appears when you invoke the Convert to instance method refactoring.
Item | Description |
---|---|
Select an instance parameter | Select the class you want the method to belong to after the conversion. All the usages of this class inside the method are replaced with |
Visibility | In this area you can change the visibility scope of the converted method. By default, the converted method will have no scope declaration (equivalent to |