How can I reference my Java Enum without specifying its type

JavaEnums

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

You can do a static import on a nested class:

import static apackage.Test.Enum.*;

Solution 3 - Java

The Test class has to be defined in a package to be importable.

With package defined in Test (IT WORKS):

package mypackage;

You can use:

import static mypackage.Test.MyEnum.*;

Without package defined, you cannot use (DOES NOT WORK):

import static Test.MyEnum.*;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBill KView Question on Stackoverflow
Solution 1 - JavaPascal ThiventView Answer on Stackoverflow
Solution 2 - JavaYishaiView Answer on Stackoverflow
Solution 3 - JavaJayenView Answer on Stackoverflow