在 IntelliJ 中重新排序 Java 类方法的简单方法?

在 IntelliJ 中,有没有比手动剪切和粘贴代码更简单的重新排序类源文件中方法的方法?现在我在重构遗留代码的时候经常需要它,例如在源代码中移动相关的方法。

在 Eclipse AFAIK 中有一个类似于 IntelliJ 的结构视图的视图,我可以在其中拖放方法。然而,这在 IntelliJ 中不起作用,我也无法从它的帮助中找到任何提示。

我正在使用 IntelliJ9.0.2来确定。

44331 次浏览

Select a block of text (hit Ctrl-W a few times) and then use Ctrl-Shift-Up and Ctrl-Shift-Down to move it around.

You can select a method name and hit: Ctrl+Shift+Up or Ctrl+Shift+Down to move it up and down.

On OS X: Cmd+Shift+Up or Cmd+Shift+Down

Beyond this the Rearranger Plugin lets you move methods around quickly, and even define a standard ordering based on your coding convention.

With your cursor on the method definition line (you do not have to and press ctrl+shift+up or ctrl+shift+down, to move up or down respectively.

You can also to ctrl+shift+numberpad - to quickly collapse everything so you can focus on moving around (plain - works on my laptop as well, not sure why) and ctrl+shift+numberpad + to get back to see everything (ctrl-shift-equals works on my laptop as well).

Not a perfect answer yet, due to a bug in IntelliJ.

Though IntelliJ offers this feature implicitly, but it needs to be enabled as well as fixed. The OP's suggested way is technically arranging methods in depth-first order. However, if you use Breadth-first ordering(which works properly), it should reduce the manual work of moving functions by a lot, by arranging all caller and callee methods together.

Issue Link: https://youtrack.jetbrains.com/issue/IDEA-149524. Please do vote for its resolution.

IntellijRearrangeMethodsInDFO

The appropriate action for this is Rearrange Code. This has no key assigned to it, but you can define your own using Preferences->Keymap.

RearrangeActionMenuButton

enter image description here

IntelliJ has a built in system that allows you to specify how to order your methods. You need to go to Settings (Ctrl + Alt +S) -> Editor -> Code Style -> Java -> Arrangement (tab) and scroll down until you find the icons with methods. There you can manipulate the options to sort them by visibility, or alphabetically, or to keep related ones grouped together. Here is a screenshot of my settings which will order methods automatically by visibility (public, protected, private) and alphabetically (a-z). The blue highlights show the currently selected rules.

enter image description here

There is an automated way, which you can later tweak

Code -> show reformat file dialog

and tick "rearrange code" box