如何在Visual Studio Code中对Java类成员进行重排与排序?
I feel your pain—Prettier is great for formatting, but it doesn’t touch the structural ordering of class members like static vars, fields, and methods. VS Code doesn’t have this natively, but there are solid extensions that replicate IntelliJ’s member organization functionality perfectly. Here are the top options:
1. Sort Java Members (Direct, Customizable Solution)
This extension is built explicitly for what you’re asking. It lets you define a custom order for all class members and rearrange them with one click or command.
- Setup Steps:
- Install it from the VS Code Marketplace.
- Open your VS Code settings (Ctrl+, / Cmd+,) and search for "Sort Java Members" to tweak the default order. You can rearrange categories like
static fields,instance fields,constructors,public methods,private methods, etc., to match your preferences. - To rearrange a file, right-click inside it and select "Sort Java Members", or use the command palette (Ctrl+Shift+P / Cmd+Shift+P) and run
Sort Java Members: Sort Current File.
2. Language Support for Java by Red Hat (Eclipse Formatter)
The official Java extension uses Eclipse’s formatting engine, which includes member organization capabilities. This is perfect if you already use Eclipse-style rules or want a more integrated solution.
- Setup Steps:
- Create a
.java-formatter.xmlfile (you can export one from Eclipse or use a template). Look for thememberOrderingsection where you can define the exact sequence of members. - In VS Code settings, set
java.format.settings.urlto the path of your.java-formatter.xmlfile. - Enable the "Organize Members" option in the formatter config. Now, when you format your code (Ctrl+Shift+F / Cmd+Shift+F), it will automatically rearrange members according to your defined order alongside formatting.
- Create a
3. CheckStyle (For Rule Enforcement + Rearrangement)
If you want to enforce member ordering as part of your project’s code style rules, CheckStyle is a great choice. Its VS Code extension can automatically fix member order to match your config.
- Setup Steps:
- Install the CheckStyle extension for VS Code.
- Create a
checkstyle.xmlconfig file and add theMemberOrderrule, specifying your desired member sequence. - Run the CheckStyle "Fix" command (via right-click or command palette) to rearrange members to comply with your rule.
All these tools let you control the structural order of your Java code—no more manually moving static vars or methods around. Pick the one that fits your workflow best!
内容的提问来源于stack exchange,提问作者Bestname

