Constant expression required记一次switch结合Enum的使用
首先
- switch的case只能使用常量,在编译时就能识别的量。
- Enum的使用
看一下代码,这是使用zookeeper的使用进行一个常规状态比较。
@Override
public void processResult(int rc, String s, Object o, Stat stat) {
boolean exists;
switch (rc) {
case KeeperException.Code.OK.intValue:
exists = true;
break;
...
}
}
这个时候就会出现Constant expression required
的报错
看一下Code 的Enum类:
public static enum Code implements KeeperException.CodeDeprecated {
OK(0),
SYSTEMERROR(-1),
RUNTIMEINCONSISTENCY(-2),
DATAINCONSISTENCY(-3),
CONNECTIONLOSS(-4),
MARSHALLINGERROR(-5),
UNIMPLEMENTED(-6),
OPERATIONTIMEOUT(-7),
BADARGUMENTS(-8),
APIERROR(-100),
NONODE(-101),
NOAUTH(-102),
BADVERSION(-103),
NOCHILDRENFOREPHEMERALS(-108),
NODEEXISTS(-110),
NOTEMPTY(-111),
SESSIONEXPIRED(-112),
INVALIDCALLBACK(-113),
INVALIDACL(-114),
AUTHFAILED(-115),
SESSIONMOVED(-118),
NOTREADONLY(-119);
private static final Map<Integer, KeeperException.Code> lookup = new HashMap();
private final int code;
private Code(int code) {
this.code = code;
}
public int intValue() {
return this.code;
}
public static KeeperException.Code get(int code) {
return (KeeperException.Code)lookup.get(code);
}
static {
Iterator i$ = EnumSet.allOf(KeeperException.Code.class).iterator();
while(i$.hasNext()) {
KeeperException.Code c = (KeeperException.Code)i$.next();
lookup.put(c.code, c);
}
}
虽然我们可以通过类中定义的intValue()方法去获取对应的Enum的int值,但是这并不是明确的(需要执行方法后才能确定对应的值),java需要明确这个值是在编译期间就能够确定的,而不是在执行过程中去确定。
正确的使用应该是:
@Override
public void processResult(int rc, String s, Object o, Stat stat) {
boolean exists;
KeeperException.Code code = KeeperException.Code.get(rc);
switch (code) {
case KeeperException.Code.OK:
exists = true;
break;
...
}
}
这个时候,在编译期间的code和OK都是确定的值。编译通过。