切换枚举值:case表达式必须是常量表达式

Ian*_*edv 10 java enums switch-statement

我有一个具有以下结构的枚举:

public enum Friends {
    Peter("Peter von Reus", "Engineer"),
    Ian("Ian de Villiers", "Developer"),
    Sarah("Sarah Roos", "Sandwich-maker");

    private String fullName;
    private String occupation;

    private Person(String fullName, String occupation) {
        this.fullName = fullName;
        this.occupation = occupation;
    }

    public String getFullName() {
        return this.fullName;
    }

    public String getOccupation() {
        return this.occupation;
    }
}
Run Code Online (Sandbox Code Playgroud)

我现在想用来switch确定变量name是否与某个变量相关联enum:

//Get a value from some magical input
String name = ...

switch (name) {
    case Friends.Peter.getFullName():
        //Do some more magical stuff
        ...
    break;
    case Friends.Ian.getFullName():
        //Do some more magical stuff
        ...
    break;
    case Friends.Sarah.getFullName():
        //Do some more magical stuff
        ...
    break;
}
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎完全合法,但我case expressions must be constant expressions在Eclipse中遇到错误.我可以使用一组简单的if语句解决这个问题,但我想知道这个错误的原因以及如果允许的话,事情可能会向南发展.

注意:我无法改变结构 Friends

Ell*_*sch 24

如果我理解你的问题,你可以使用valueOf(String)喜欢

String name = "Peter";
Friends f = Friends.valueOf(name);
switch (f) {
case Peter:
    System.out.println("Peter");
    break;
case Ian:
    System.out.println("Ian");
    break;
case Sarah:
    System.out.println("Sarah");
    break;
default:
    System.out.println("None of the above");
}
Run Code Online (Sandbox Code Playgroud)

还有,这个

private Person(String fullName, String occupation) {
    this.fullName = fullName;
    this.occupation = occupation;
}
Run Code Online (Sandbox Code Playgroud)

应该

private Friends(String fullName, String occupation) {
    this.fullName = fullName;
    this.occupation = occupation;
}
Run Code Online (Sandbox Code Playgroud)

因为Person!= Friends.

编辑

根据您的评论,您需要编写一个静态方法来获取正确的Friends实例,

    public static Friends fromName(String name) {
        for (Friends f : values()) {
            if (f.getFullName().equalsIgnoreCase(name)) {
                return f;
            }
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

然后你可以打电话给,

    String name = "Peter von Reus";
    Friends f = Friends.fromName(name);
Run Code Online (Sandbox Code Playgroud)

valueOf(String)将匹配枚举字段的名称.所以"伊恩","莎拉"或"彼得".


Jon*_*eet 12

这对我来说似乎完全合法

嗯,不是 - 方法调用永远不是一个常量表达式.有关常量表达式的构成,请参见JLS 15.28.案例值总是必须是一个常量表达式.

最简单的解决方法是使用一个Friend.fromFullName静态方法,这可能看起来像Friend一个HashMap<String, Friend>.(你不具备有这种方法中Friend,当然......它只是将是最传统的地方.)然后,你可以切换的枚举,而不是名称.

作为旁注,你的枚举名称应该是单数的,并且有ALL_CAPS成员,所以Friend.PETER等等.