好吧.. Java 中的枚举类似乎比它们的 C 或 C++ 类更通用,但对于这个特定的代码结构,我试图设计它们的对象性质只会给我带来麻烦。
我的是这样的:
public static enum ServerResponse{
SIGN_UP_SUCESS(0),
INTERNAL_SERVER_ERROR(1),
EMAIL_ALREADY_REGISTERED(2),
SIGNIN_FAILED(3),
WAITING_CONFIRMATION(4),
SIGNIN_SUCESS(5),
BLOCKED_ACCOUNT(6),
INACTIVE_ACCOUNT(7);
private final int numcode;
ServerResponse(int num){
numcode = num;
}
final int numCode(){ return numcode;}
}
你看现在问题出现了,因为服务器给我一个数字响应,我不能直接与枚举类进行比较。然后我的想法是创建 numCode() 方法,该方法将返回实例化枚举的整数属性。我试图做这样的事情:
int SERVER_RESPONSE = ServerInterface.sendRequest();
switch(SERVER_RESPONSE){
ServerInterface.ServerResponse.BLOCKED_ACCOUNT.numCode():
//Do something
ServerInterface.ServerResponse.INTERNAL_SERVER_ERROR:
}
但正如您想象的那样,以上方法均无效。第一种情况比较提示“情况表达式必须是常量表达式”,而第二种类型只是给我一个类型不匹配错误。
那么我应该怎么做呢?好吧,现在我正在做这样的事情:
for(ServerResponse response : ServerResponse.values()){
if(response.numCode() == SERVER_RESPONSE){
return response;
}
}
但这很难看..我想使用 switch 语句,毕竟这就是枚举类型的全部目的,对吗?那么请问,我在这里缺少什么?
谢谢
尼尔森
最佳答案
您在枚举中缺少一个将整数映射到枚举值的方法。具体如何操作取决于您 - 如果您的整数是从 0 开始的连续整数,您可能会使用数组...或者您可以使用 Map<Integer, ServerResponse>
.无论哪种方式,您都可以执行以下操作:
// Please don't use caps for non-constants
int serverResponseNumber = ServerInterface.sendRequest();
ServerResponse serverResponse = ServerResponse.fromInt(serverResponseNumber);
if (serverResponse == null) {
// Do something with an unknown response - switch will barf otherwise.
// Possibly throw an exception yourself?
}
switch(serverResponse) {
case SIGN_UP_SUCCESS:
...
}
关于java - 具有应映射到枚举类型的整数值的 Switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7117503/