在Java中将字段的值定义为常量

xel*_*lon 4 java oop constants

我正在将标准实现为Java中的面向对象库.标准包括通过终端通过网络传递的许多消息.每条消息都作为单个类实现.

某些字段表示为char类型,这些字段具有标准中定义的值之一.例如,

public class OutgoingMessage {
    private char action;
Run Code Online (Sandbox Code Playgroud)

并且行动有这些价值,

'0' - Do not print
'1' - Print
'2' - Print and Forward
'3' - Print and Reply
'F' - Forward
'R' - Reply
Run Code Online (Sandbox Code Playgroud)

还有一些类有两个以上这样的字段.在这些情况下,将它们定义为类中的常量可能会很混乱.

所以我试图将这些值实现为

public class OutgoingMessage {
    private char action;

    public final class ActionTypes {
        public static final char DO_NOT_PRINT = '0';
        public static final char PRINT = '1';
        ...
Run Code Online (Sandbox Code Playgroud)

并使用如下

...
message.setAction(OutgoingMessage.ActionTypes.DO_NOT_PRINT);
...
message.setFooBar(OutgoingMessage.FooBarTypes.FOO_BAR);
...
Run Code Online (Sandbox Code Playgroud)

你怎么看?这种方法有什么问题吗?你会如何在库中定义这些常量?

非常感谢

Boh*_*ian 8

使用优先级intchar常量的枚举:

public enum Action {
    DoNotPrint,
    Print,
    PrintAndForward,
    PrintAndReply,
    Forward,
    Reply
}

public class OutgoingMessage {
     private Action action;
Run Code Online (Sandbox Code Playgroud)

如果您需要将a char与操作相关联,请执行以下操作:

public enum Action {
    DoNotPrint('0'),
    Print('1'),
    PrintAndForward('2'),
    PrintAndReply('3'),
    Forward('F'),
    Reply('R');

    private static Map<Character, Action> map = new HashMap<Character, Action>() {{
        for (Action action : Action.values()) {
            put(action.getChar(), action);
        }
    }};

    private final char c;

    private Action(char c) {
        this.c = c;
    }

    public char getChar() {
        return c;
    }

    public static Action parse(char c) {
        if (!MapHolder.map.containsKey(c))
            throw new IllegalArgumentException("Invalid char: " + c);
        return MapHolder.map.get(c);
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是使用parse方法的方法:

public static void main(String[] args) {
    System.out.println(Action.parse('2')); // "PrintAndForward"
    System.out.println(Action.parse('x')); // throws IllegalArgumentException
}
Run Code Online (Sandbox Code Playgroud)

  • +1,这几乎是实现常量的新标准.这更好,因为它是类型安全的. (4认同)