如何在不指定其类型的情况下引用我的Java Enum

问题描述:

我有一个类定义自己的枚举,如下所示:

I have a class that defines its own enum like this:

public class Test
{
    enum MyEnum{E1, E2};

    public static void aTestMethod() {
        Test2(E1);  // << Gives "E1 cannot be resolved" in eclipse.
    }
    public Test2(MyEnum e) {}
}

如果我指定MyEnum.E1它可以正常工作,但我真的只想把它作为E1。任何想法如何才能完成这个,或者是否必须在另一个文件中定义这个工作?

If I specify MyEnum.E1 it works fine, but I'd really just like to have it as "E1". Any idea how I can accomplish this, or does it have to be defined in another file for this to work?

结论:
我还没有获取导入的语法正确。由于有几个答案表明这是可能的,所以我要选择一个给我需要的语法,并且提醒别人。

CONCLUSION: I hadn't been able to get the syntax for the import correct. Since several answers suggested this was possible, I'm going to select the one that gave me the syntax I needed and upvote the others.

顺便说一下,一个真正的变化这一部分(在我得到静态导入工作之前),我写的使用枚举的switch语句不允许枚举以其类型为前缀 - 所有其余代码都需要它。伤害我的头。

By the way, a REALLY STRANGE part of this (before I got the static import to work), a switch statement I'd written that used the enum did not allow the enum to be prefixed by its type--all the rest of the code required it. Hurt my head.

其实你可以做一个静态导入。下面的代码编译好:

Actually, you can do a static import of a nested enum. The code below compiles fine:

package mypackage;

import static mypackage.Test.MyEnum.*;

public class Test
{
    enum MyEnum{E1, E2};

    public static void aTestMethod() {
        Test2(E1);  
    }

    public static void Test2(MyEnum e) {}
}