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

编程入门 行业动态 更新时间:2024-10-27 02:23:11
本文介绍了如何在不指定其类型的情况下引用我的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

本文发布于:2023-07-22 13:36:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1187970.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:情况下   类型   如何在   Enum   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!