如何在不指定其类型的情况下引用我的 Java Enum [英] How can I reference my Java Enum without specifying its type

查看:22
本文介绍了如何在不指定其类型的情况下引用我的 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) {}
}

这篇关于如何在不指定其类型的情况下引用我的 Java Enum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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