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

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

问题描述

  public class Test 
{
/ / ...
public enum状态{
已打开,
已关闭,
等待
}
// ...
}

我在另一个类文件中有一个不同的类(但在同一个项目/文件夹中):

  public class UsingEnums 
{
public static void Main(String [] args)
{
测试test = new Test(); // new Test对象(存储枚举)

switch(test.getStatus())//返回当前状态
{
case Status.Opened:
/ /做某事
//休息和其他情况
}
}
}

我将在一个类中实际使用一个枚举,用于另一个类(在我的情况下,特别是在switch-case语句中)。



但是,当我这样做时,我会收到如下错误:


找不到符号 - 类状态


我如何解决这个问题?

解决方案

标签必须是枚举常量的不合格的名称:

  switch(test.getStatus()) //返回当前状态
{
case打开:
//做某事
// break和其他情况
}

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



此要求由 JLS§14.11

  SwitchLabel:
case ConstantExpression:
case EnumConstantName:
默认值:

EnumConstantName:
标识符

(感谢Mark Peters的相关帖子供参考。)


If I had a class in Java like this:

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

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

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:

cannot find symbol - class Status

How would I fix that?

解决方案

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
}

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.

This requirement is specified by JLS §14.11:

SwitchLabel:
   case ConstantExpression :
   case EnumConstantName :
   default :

EnumConstantName:
   Identifier

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

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

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