简体   繁体   中英

Variable of type of enum class

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM