Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reference my Java Enum without specifying its type

Tags:

java

enums

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

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.

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.

like image 580
Bill K Avatar asked Nov 04 '09 22:11

Bill K


People also ask

Are Java enums reference types?

Enums are reference types, in that they can have methods and can be executed from command line as well , if they have main method.

Is enum pass by reference Java?

In Java you cannot pass any parameters by reference. The only workaround I can think of would be to create a wrapper class, and wrap an enum. Now, reference will contain a different value for your enum; essentially mimicking pass-by-reference.

Can enum have different data types?

I must answer a resounding no because actually you can't. Enums have their own data type and each enum is essentially a new data type.

Can we import enum in Java?

All enums implicitly extend java. As a class can only extend one parent in Java, so an enum cannot extend anything else.


1 Answers

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) {} } 
like image 188
Pascal Thivent Avatar answered Sep 22 '22 07:09

Pascal Thivent