如何阻止Eclipse格式化程序将所有枚举放在一行上

Met*_*ome 102 java eclipse formatter

我有这样的枚举:

public static enum Command
{
login,
register,
logout,
newMessage
}
Run Code Online (Sandbox Code Playgroud)

格式化文件时,输出变为:

public static enum Command 
{
login, register, logout, newMessage
}
Run Code Online (Sandbox Code Playgroud)

Pol*_*ick 193

@wjans的答案适用于普通枚举,但不适用于带参数的枚举.为了扩展他的答案,这里是Eclipse Juno中为我提供最合理格式的设置:

  1. Window> Preferences> Java> Code Style>Formatter
  2. 点击 Edit
  3. 选择Line Wrapping选项卡
  4. 选择enum声明treenode
  5. 设置Line wrapping policyWrap all elements, every element on a new line (...)现在它在括号中表示3中的3.
  6. 取消选中Force split, even if line shorter than maximum line width (...),现在它在括号中显示3个中的3个.
  7. 选择Constantstreenode
  8. 校验 Force split, even if line shorter than maximum line width

这将enum treenode的3个子节点设置为相同的包装策略,并且除了Constantstreenode 之外的相同的强制拆分策略,因此带有参数的枚举将在每个行上自行格式化.参数只有在超过最大线宽时才会换行.

例子:

@wjans

enum Example {
    CANCELLED,
    RUNNING,
    WAITING,
    FINISHED
}

enum Example {
    GREEN(
        0,
        255,
        0),
    RED(
        255,
        0,
        0)
}
Run Code Online (Sandbox Code Playgroud)

上述解决方案:

enum Example {
    CANCELLED,
    RUNNING,
    WAITING,
    FINISHED
}

enum Example {
    GREEN(0, 255, 0),
    RED(255, 0, 0)
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,您可以从 eclipse-codeformatter.xml 发布相应的 XML 标记吗? (2认同)

wja*_*ans 49

您可以在格式化程序首选项中指定:

  • 首选项:Java - 代码样式 - 格式化程序
  • 单击编辑
  • 选择"Line Wrapping"选项卡
  • 在左侧的框中选择"枚举"声明 - >常量
  • 将换行策略设置为'换行所有元素,新行上的每个元素'
  • 检查'强制拆分......'


Rak*_*aku 11

它也有点丑陋,但是如果你的公司政策阻止你更改格式化程序,你可以在你不想被包装的行的末尾添加注释.

public static enum Command 
{
    login,//
    register,//
    logout,//
    newMessage//
};
Run Code Online (Sandbox Code Playgroud)


pil*_*rth 5

它不是很好但你可以关闭某些代码部分的Eclipse格式化程序...

// @formatter:off
public static enum Command {
    login,
    register,
    logout,
    newMessage
};
// @formatter:on
Run Code Online (Sandbox Code Playgroud)

该选项位于Windows-> Preferences-> Java-> Code Style-> Formatter-> Edit-> Off/On Tags面板