Ztyx
Ztyx

Reputation: 14908

Extracting class in Eclipse

This must be possible but I just can't figure it out in Eclipse. I have

/** ClassA.java */
class A {
  ...
}

class B {
  ...
}

and I'd like to select class B and extract to its own file so that I get:

/** ClassA.java */
class A {
  ...
}

and

/** ClassB.java */
class B {
  ...
}

How do I do this in Eclipse?

Upvotes: 7

Views: 6031

Answers (5)

Buhake Sindi
Buhake Sindi

Reputation: 89169

There's no functionality that I know of. You will have to create a java file of choice and cut-paste the class in the new file. Fix the imports and package declaration names (if need be).


EDIT The best way to do it: Simply create a blank file B.java, go back to A.java, highlight B.java and right click and select Refactor -> Move (Alt+Shift+V for short). It will move the class B to B.java.

I have tested and it works. You might need to manage imports if necessary.

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

Position the caret somewhere inside class B (maybe it has to be inside the class name). Select Refactor -> Move type to new File.

(That's the action name in Eclipse 3.6. I believe in earlier versions it was Move member type to top level)

Reference:

Upvotes: 0

Bert F
Bert F

Reputation: 87533

In my Eclipse (3.6 - Helios SR1), I highlight the type name (B), and then right-click for the pop-up menu and then select Refactor > Move Type to New File ....

Edit: It was called 'Convert Member Type to Top Level' in earlier verions, but has been updated to work with more than just member types:

http://download.eclipse.org/eclipse/downloads/drops/R-3.6-201006080911/eclipse-news-part2.html

Move type to new file refactoring.

The Convert Member Type to Top Level refactoring has been renamed to Move Type to New File and now allows any secondary type in a file to be moved into its own file. The action continues to work for member types.

Upvotes: 6

aioobe
aioobe

Reputation: 420951

This is how you do it (works in Eclipse 3.5):

  1. Select your code to extract:

    /** ClassB.java */
    class B {
      ...
    }
    
  2. Cut

  3. Right click on the package in which you want to put it

  4. Select paste. (Then Organize imports if needed.)

Upvotes: 12

Mark Peters
Mark Peters

Reputation: 81074

If there's no specific function, then creating the new class, copy and pasting the contents of B and then hitting CTRL-SHIFT-O on both files (or at least A.java) to clean up the imports should do it.

It's not a very common thing to ask for, and it's pretty easy to do manually.

Edit: You can also create B.java and then use Refactoring->Move on B in your A.java to move it to B.java. It didn't seem to copy over the imports though when I did that, whereas when I copied and pasted manually it grabbed the imports automatically.

Upvotes: 1

Related Questions