带字符串的 switch 中需要常量表达式

constant expression required in switch with string

我已经声明了这个枚举 class:

public enum class RoleName {
    Worker,
    Boss
}

我想在开关/外壳中使用它

switch (requestRole.getName()) {
    case RoleName.Worker.name():

但是我有这个编译错误

constant expression required 

如果我删除 class,我会收到此 IntelliJ IDEA 错误:'class' keyword is expected after 'enum;

这里有两个错误:

  1. 枚举的定义中不应包含 class。根据经验,常量应该是大写的。

    enum RoleName {
        WORKER,
        BOSS;
    }
    
  2. RoleName.Worker.name() 不允许作为 case 表达式,因为它不是 a constant expression. You could transform requestRole.getName() into a RoleName and use it as a switch expression.

    switch (RoleName.valueOf(requestRole.getName())) {
        case WORKER: /* ... */ break;
    }