使用 Java 中的常量:如何记录给定的名称?

Working with constants in Java: How to log the name given to them?

假设我们有一个 class 看起来像这样:

public class UserAction {

    static final int ACTION_USER_WANTS_TO_DO_A = 1001;
    static final int ACTION_USER_WANTS_TO_DO_B = 1002;
    // ...

    // 'sub-grouping'
    static final int[] ALL_ACTIONS_ALLOWED_IN_STATE_X = {
        ACTION_USER_WANTS_TO_DO_A,
        ACTION_USER_WANTS_TO_DO_D,
        ACTION_USER_WANTS_TO_DO_Q,
        // ... 
    }

}

... 另一个 class 看起来像这样:

public class Model {

    public void onActionableEvent(int action) {

        // check for state mismatch by iterating over sub-groups
        // if (fail) {return;}, if pass:

        Log.i("XXX","processing: " + action); // <----- this is the problem.

        switch (action) {
            case: .ACTION_USER_WANTS_TO_DO_A: {
                //
                break;
            }
            case: .ACTION_USER_WANTS_TO_DO_B: {
                //
                break;
            }
        }
    }

}

我在记录操作的实际名称而不是原始 int 时遇到问题...而没有执行一大堆低效代码 -- 例如。在每个 case 块中分别记录原始字符串,使用 Hashmap,其中重构名称将变得很麻烦。

我的问题是:可以使用什么数据结构来:

1) 允许 'UserActions' 像在 UserAction class 中一样被分组——以一种可以迭代子组的方式。 (例如,这排除了 Enum)。

2) 将在日志中显示操作的实际名称(例如.toString()),而不是仅显示实际的int 值(数字)? (似乎排除了 int... 这就是我正在使用的)。

3) 可以像示例中那样静态使用,而不必构造 UserAction 的实例。

我会说 enum 是您所需要的。像这样:

enum USER_ACTIONS { ACTION_USER_WANTS_TO_DO_A, ACTION_USER_WANTS_TO_DO_B };

并尝试回答您的 3 个问题:

1) 它们被分组在 enum

2) 在日志中你会得到 processing: ACTION_USER_WANTS_TO_DO_A

3) 是