Java: general enumeration type only

Assuming I have a basic enum like:

public enum Color { Red, Green, Blue} 

How to write one generic class that only accepts “enum classes” so that a particular instance of this generic class would look like MyClass<Color> ?

Edit:

What you really need to do is write a generic abstract class containing a function that returns all enumerations of the "record" in a 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() not. What am I doing wrong here?

+6
source share
5 answers
 public class EnumAcceptor<E extends Enum<E>> { ... } 

Use E as a type inside your class.

+5
source

See Istvan Day for an answer to the original question.

For subsequent actions, methods like values() are static methods, so you're out of luck trying to get this from a common parameter. As a bad solution, you can pass the enum Class object to the constructor. and use Class.getEnumConstants . But you could also pass MyEnum.values() to the constructor, not to the class, and avoid full reflection. This is a real shame, there is no sensible metaclass enum.

+4
source

An enum does indeed declare a class derived from enum . So you can use:

 public class MyClass<T extends Enum> { } 
+1
source

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

Although you cannot pass enum itself as a parameter (since it actually does not have an object equivalent), you can specify that you should get class enum in your constructor and get enum details from this:

 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); } } 
0
source

You cannot use E.values() due to type erasure - type E not available at run time.

For a specific case in your question, you are probably better off using Guava Lists.newArrayList :

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

Source: https://habr.com/ru/post/920516/


All Articles