枚举枚举值:case表达式必须是常量表达式 [英] switch over value of enum: case expressions must be constant expressions

查看:240
本文介绍了枚举枚举值:case表达式必须是常量表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an enum with the following structure:

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;
    }
}

我现在想使用 switch 确定如果一个变量 name 与某个枚举相关联

I would now like to use switch to determine, if a variable name is associated with a certain 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;
}

这对我来说似乎完全合法,但是我收到错误 case表达式必须是Eclipse中的常量表达式
我可以用一组简单的if语句来解决这个问题,但是我想知道这个错误的原因,如果允许的话,我可以向南推荐。

This seems perfectly legal to me, but I'm getting the error case expressions must be constant expressions in Eclipse. I can get around this with a simple set of if statements but I would like to know the reason for this error and how things might go south if this was allowed.

注意:我不能更改朋友的结构

推荐答案


这似乎对我来说完全合法

This seems perfectly legal to me

这不是 - 一种方法调用是永远不会一个常量表达式。有关构成常量表达式的内容,请参阅 JLS 15.28 。一个案例值总是必须是一个常量表达式。

Well it's not - a method call is never a constant expression. See JLS 15.28 for what constitutes a constant expression. And a case value always has to be a constant expression.

最简单的修复是将一个 Friend.fromFullName static方法,可以在 HashMap< String,Friend> 中查看 Friend 。 (你不 要在 Friend 中有这个方法,那当然是这是最传统的地方。)然后你可以切换枚举而不是名称。

The simplest fix would be to have a Friend.fromFullName static method, which perhaps looked the Friend up in a HashMap<String, Friend>. (You don't have to have that method in Friend of course... it's just that would be the most conventional place.) Then you could switch over the enum rather than the name.

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

As a side note, your enum name should be in the singular and with ALL_CAPS members, so Friend.PETER etc.

这篇关于枚举枚举值:case表达式必须是常量表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆