使用不同类的Java枚举? [英] Using Java enums from different classes?

查看:158
本文介绍了使用不同类的Java枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像Java这样的类:

If I had a class in Java like this:

public class Test
{
    // ...
    public enum Status {
        Opened,
        Closed,
        Waiting
    }
    // ...
}

我在不同的类文件(但是在同一个项目/文件夹)有一个不同的类: p>

And I had a different class in a different class file (but in the same project/folder):

public class UsingEnums
{
    public static void Main(String[] args)
    {
        Test test = new Test(); // new Test object (storing enum)

        switch(test.getStatus()) // returns the current status
        {
            case Status.Opened:
                // do something
            // break and other cases
        }
    }
}

我有效地在一个类中使用枚举,在另一个类中使用(在我的情况下,特别是在switch-case语句中)。

I would effectively have an enum in one class that is used in another class (in my case, specifically in a switch-case statement).

但是,当我这样做,我得到一个错误像:

However, when I do that, I get an error like:


找不到符号 - 类Status

cannot find symbol - class Status

如何解决这个问题?

推荐答案

标签必须是枚举常量的未限定的名称:

An enum switch case label must be the unqualified name of an enum constant:

switch (test.getStatus()) // returns the current status
{
    case Opened:
        // do something
        // break and other cases
}

在另一个类中定义它并不重要。在任何情况下,编译器都能够根据您的 switch 语句来推断枚举的类型,并且不需要对常量名进行限定。无论什么原因,使用限定名称都是无效语法。

It doesn't matter that it's defined within another class. In any case, the compiler is able to infer the type of the enum based on your switch statement, and doesn't need the constant names to be qualified. For whatever reason, using qualified names is invalid syntax.

此要求由 JLS§14.11

SwitchLabel:
   case ConstantExpression :
   case EnumConstantName :
   default :

EnumConstantName:
   Identifier

(感谢Mark Peters的相关文章以供参考。)

(Thanks to Mark Peters' related post for the reference.)

这篇关于使用不同类的Java枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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