gpt4 book ai didi

java - 在 Java 中使用常量 : How to log the name given to them?

转载 作者:行者123 更新时间:2023-11-29 23:28:03 26 4
gpt4 key购买 nike

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

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,
// ...
}

}

...和另一个看起来像这样的类:

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 block 中分别记录原始字符串,使用 Hashmap 重构名称将变得很麻烦。

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

1) 允许对“UserActions”进行分组,因为它们在 UserAction 类中 - 以一种可以迭代子组的方式。 (例如,这排除了 Enum)。

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

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

最佳答案

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

枚举 USER_ACTIONS {
ACTION_USER_WANTS_TO_DO_A,
ACTION_USER_WANTS_TO_DO_B
};

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

1) 它们在枚举

中分组

2) 在日志中您将得到处理:ACTION_USER_WANTS_TO_DO_A

3)是

关于java - 在 Java 中使用常量 : How to log the name given to them?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53172032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com