Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring static methods into instance methods in Eclipse

How can I refactor

class Plugh {
    static void foo(Bar bar);
}

into

class Bar {
    void foo();
}

using Eclipse? IOW make the static methods into instance methods of one of the arguments.

like image 438
peter.murray.rust Avatar asked Dec 24 '10 18:12

peter.murray.rust


People also ask

How do you convert a static method to an instance method in Java?

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 as String . From the main menu, select Refactor | Convert to Instance Method. You can also use a context menu to access this refactoring.

How do I refactor a method in Eclipse?

Changing a Method Signature Select the method or place the cursor somewhere inside. Right-click and choose Refactor > Change Method Signature.

Can static methods invoke instance methods?

A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.

What are the type of refactoring in Eclipse?

Refactoring using EclipseRight clicking on a Java element in the Package Explorer view and selecting Refactor menu item. Right clicking on a Java element in the Java editor and selecting Refactor menu item. Selecting a Java element in either the Package Explorer view or Java Editor and clicking Shift + Alt + T.


2 Answers

Remove the "static" keyword and then do the "Move Method" refactoring. It should offer "Bar" as a target class.

(It seems crazy to me that Eclipse only does this for non-static methods, but that is the way it works. Seems like a bug to me. Maybe I should work up a contribution to fix it, instead of just complaining about it! ;-)

like image 185
Jeff Grigg Avatar answered Oct 13 '22 01:10

Jeff Grigg


I don't believe there's a fully automated way to do this, but what I would do is to make the body of Plugh.foo() call bar.foo(), then use Quick Fix (control-1) to create Bar.foo(), then cut & paste the (rest of) the body of Plugh.foo() into Bar.foo().

Then inline all calls to Plugh.foo(), and do an initial assignment inside Bar.foo(): Bar bar = this;, then inline the local (and probably clean up all the this.'s in the method).

like image 22
Carl Manaster Avatar answered Oct 13 '22 00:10

Carl Manaster