tags:

views:

388

answers:

3

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.

+1  A: 

If you just want to be able to refer to E1 within your class, you could define a constant variable called E1 in your class:

enum MyEnum{E1, E2};

private static final MyEnum E1 = MyEnum.E1;
Phil Ross
At that point, I might as well go back to ints--much less verbose/boilerplate.
Bill K
Really?? You'd throw out the dozens of great advantages of enums over ints that easily? Anyway, though, import static is the right answer.
Kevin Bourrillion
+5  A: 

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) {}
}
Pascal Thivent
I alluded to this as a solution in my question, but I'd really rather not do that. The enums are only used inside this one file. It just seems strange that this doesn't just automatically work.
Bill K
Although you have to use a static import, you do not need to define it in its own class.
Yishai
I tried in a few ways and can't get the static import to resolve correctly when it refers to a class inside the class doing the import.
Bill K
@Yishai Yeah, I noticed that when doing some testing.
Pascal Thivent
@Bill K weird, are you sure you tried `import static mypackage.Test.MyEnum.*;`?
Pascal Thivent
@Bill K, why do you think it should automatically work? How would you expect this to work then?class A { enum B {X,Y}; enum C {X,Z}; }
Kevin Bourrillion
+1  A: 

You can do a static import on a nested class:

import static apackage.Test.Enum.*;
Yishai