Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can eclipse convert/refactor a method to a class?

This seems like it should be fairly straight-forward, but I can't see anything obvious. What I basically want to do it to point at a method and refactor->extract class. This would take the method in question to a new class with that method as top level public API. The refactoring would also drag any required methods and variables along with it to the new class, deleting them from the old class if nothing else in the old class is using it.

This is a repetitive task I often encounter when refactoring legacy code. Anyway, I'm currently using Eclipse 3.0.2, but would still be interested in the answer if its available in a more recent version of eclipse. Thanks!

like image 491
Chris Knight Avatar asked Aug 02 '10 12:08

Chris Knight


People also ask

How do I Refactor a method 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.

How do I move a method to another class in Eclipse?

To move this method to the new class, highlight the method's name and select Refactor→ Move, or right-click and select Refactor→ Move, opening the Move Static Member(s) dialog shown in Figure 4-5. In Eclipse, you can move a static method, static field, or instance method using refactoring.

Does Eclipse support refactoring?

EMF Refactor is an Eclipse open source tool environment conveniently supporting a structured model quality assurance process.


2 Answers

I don't think this kind of refactoring exists yet.

Bug 225716 has been log for that kind of feature (since early 2008).
Bug 312347 would also be a good implementation of such a refactoring.

"Create a new class and move the relevant fields and methods from the old class into the new class."

I mention a workaround in this SO answer.

like image 88
VonC Avatar answered Oct 05 '22 06:10

VonC


In Eclipse 3.7.1 there is an option to move methods and fields out of a class. To do so:

  1. Make sure the destination class exists (empty class is fine, just as long as it exists in the project).
  2. In the source class, select the methods that you want to remove (the outline view works great for this), right click on the selection, and choose Move
  3. Select the destination class in the drop down/Browse

Your members are now extracted. Fix any visibility issues (Source > Generate Getters and Setters is very useful for this) and you are all set.

like image 22
Konstantin Tarashchanskiy Avatar answered Oct 05 '22 08:10

Konstantin Tarashchanskiy