开发者

Extracting class in Eclipse

开发者 https://www.devze.com 2023-01-23 12:30 出处:网络
This must be possible but I just can\'t figur开发者_如何转开发e it out in Eclipse. I have /** ClassA.java */

This must be possible but I just can't figur开发者_如何转开发e 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?


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.)


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.


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.


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.


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:

  • What's new in Eclipse 3.6? (Refactoring)
0

精彩评论

暂无评论...
验证码 换一张
取 消