views:

267

answers:

2

I was hoping to declare in Enum type in a subclass and then access it from the super class. This is what I came up with, but it does not work:

class Subclass {
 enum Pets {
  CAT,
  DOG;
 }

Class<Pets> getEnumClass() {
    return Pets.class;
 }
}

class Superclass  {
    // This generates a warning: 
abstract Class<? extends Enum> getEnumClass(); 
void PrintEnumNames() throws InstantiationException, IllegalAccessException {
Class<? extends Enum> enumClass = getEnumClass();

Enum newEnum = enumClass.newInstance();
 for( Enum iEnum : newEnum.values()) { // newEnum.values() isn't available
    System.out.printf("%s", iEnum.toString());
   }
 }
}
+2  A: 

values() is a static method, you can't call it on the instance. To get enum values from the class, use Class.getEnumConstants():

Class<? extends Enum> enumClass = getEnumClass(); 
for (Object o: enumClass.getEnumConstants())
    System.out.println(o);
axtavt
+2  A: 

Actually, you can call static methods on instances, but it is not possible to get an instance of an Enum this way. That is, this line won't work, and will throw an InstantiationException every time.

Enum newEnum = enumClass.newInstance();

This is because Enums are restricted in the values that they can have, and these values are set by the JVM when the class is initialised (Pets.CAT and Pets.DOG, in your example).

Daniel