2

I need to specify an Enum class as a class variable in another Enum like so:

enum A {}
enum B {
  Class<Enum> clazz;
}

So that clazz can point to any Enum class like A or B or any other. Is it possible to do it in Java?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Artem
  • 7,275
  • 15
  • 57
  • 97

1 Answers1

2

tl;dr

Declare a member field:

public Class< ? extends Enum > clazz ;

Details

Apparently yes, you can hold a enum Class object as a member field on another enum’s class definition.

In this example code we define our own enum, Animal, providing for two named instances. Our enum carries a member field of type Class. In that member field, we store either of two enum classes passed to the constructor. We pass enum classes defined in the java.time package, DayOfWeek amd Month.

    enum Animal { 
        // Instances.
        DOG( DayOfWeek.class ) , CAT( Month.class )  ;

        // Member fields.
        final public Class clazz ;

        // Constructor
        Animal( Class c ) {
            this.clazz = c ;
        }
    }

Access that member field.

System.out.println( Animal.CAT.clazz.getCanonicalName() ) ;

Run this code live at IdeOne.com.

java.time.Month

If you want to restrict your member field to hold only Class objects that happen to be enums, use Java Generics. Enums in Java are all, by definition, implicitly subclasses of Enum.

    enum Animal { 
        DOG( DayOfWeek.class ) , CAT( Month.class )  ;
        final public Class< ? extends Enum > clazz ;
        Animal(  Class< ? extends Enum > c ) {
            this.clazz = c ;
        }
    }

In that code above, change the Month.class to ArrayList.class to get a compiler error. We declared our clazz member field as holding a Class object representing a class that is a subclass of Enum. The Month class is indeed a subclass of Enum while ArrayList.class is not.

Run that code with generics live at IdeOne.com.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Technically, this is correct, but `EnumSet.allOf(clazz)` won't work – Artem Feb 23 '21 at 04:21
  • 1
    @Artem (a) You did not ask for `EnumSet.allof( clazz )` in your Question. (b) See [`Class#getEnumConstants()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getEnumConstants()). The Javadoc says: *Returns the elements of this enum class or null if this Class object does not represent an enum type.* So code would be: `Animal.CAT.clazz. getEnumConstants()` to get an array of all the months of the year. Feed that array to [`Set.of()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E...)) for an unmodifiable set of the enums. – Basil Bourque Feb 23 '21 at 04:35