8

Assuming that I have a basic enum like:

public enum Color { Red, Green, Blue}

How can one write a generic class which only accepts "enum classes" so that a concrete instantiation of that generic class might look like MyClass<Color>?

Edit:

What a actually want to do is to write a generic abstract class containing a function returning all enum "entries" as list:

public abstract class EnumListBean<E extends Enum<E>> {

    public List<E> getEnumList() {
        return Arrays.asList(E.values());
    }

}

While Day.values() is available E.values() is not. What i am doing wrong here?

1
  • No its implementation should not be limited to one concrete enum type but to arbitrary enum types. I just used Day to describe more concretely what i want. Commented Jul 15, 2012 at 11:49

5 Answers 5

7
public class EnumAcceptor<E extends Enum<E>> {
    ...
}

Use E as a type inside your class.

Sign up to request clarification or add additional context in comments.

Comments

4

See Istvan Devai for answer to original question.

For the follow up, methods like values() are static methods, so you're out of luck trying to get that from a generic parameter. As a poor solution, you can pass the enum's Class object into the constructor. and use Class.getEnumConstants. But you might as well pass MyEnum.values() into the constructor rather than the class, and so avoid reflection altogether. It's a real shame there isn't a sensible enum metaclass.

Comments

1

An enum really declares a class derived from Enum. As such, you can use:

public class MyClass<T extends Enum> { }

1 Comment

You're mixing generics and raw types.
1

Note that @Istvan's solution can only accept elements of the enum, which is fine if that is all you want.

Although you cannot pass the enum itself as a parameter (because it does not actually have an object equivalent) you can specify that you must receive the class of the enum in your constructor and derive the enum's details from that:

public class EnumAcceptor<E extends Enum<E>> {
  public EnumAcceptor(Class<E> c) {
    // Can get at the enum constants through the class.
    E[] es = c.getEnumConstants();
  }

  enum ABC {
    A, B, C;
  }

  public static void main(String args[]) {
    EnumAcceptor<ABC> abcAcceptor = new EnumAcceptor<ABC>(ABC.class);
  }
}

1 Comment

Oops - duplicate of @Tom's post - sorry Tom :(
0

You can't use E.values() due to type erasure -- the type of E is not available at run-time.

For the specific case in your question, you're probably better off using Guava's Lists.newArrayList:

List<Color> days = Lists.newArrayList(Color.values());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.