Weird behaviour while overriding enum method. Is getClass().getInterfaces() working properly?

StackOverflow https://stackoverflow.com/questions/23688253

  •  23-07-2023
  •  | 
  •  

Domanda

I'll try to be as succint as possible:

Consider the interface:

package com.stackoverflow;

public interface Printable {
  void print();
}

I created an enum that implements this interface. So far so good:

public enum MyEnum implements Printable {
  ERROR,
  WARNING, 
  SUCCESS;

   @Override
   public void print() {
     System.out.println("Printed: " +this.name());
   }
}

I created a main method with the following lines:

//OK! Prints 1
System.out.println(ERROR.getClass().getInterfaces().length); 

//OK! Prints "Printable" (the name of the interface).       
System.out.println(ERROR.getClass().getInterfaces()[0].getSimpleName()); 

Everything working as expected, right? Now to the weird part:

public enum MyEnum implements Printable {
  ERROR,
  WARNING{

   //Notice the "@Override", that means that I'm overriding a superclass/interface method! No compiler errors!
   @Override
   public void print() {
     System.out.println("I'm not printable anymore!");
   }
 },
 SUCCESS;

 @Override
 public void print() { 
   System.out.println("Printed: " +this.name());
 }
}

Question:

Why, do overriding the print method makes enumInstance.getClass().getInterfaces() not to return Printable? In the example above, I know that WARNING now is part of an anonymous class, but getInterfaces isn't supposed to return the declared interfaces (Printable in this case)?

//OK! Prints 1
System.out.println(ERROR.getClass().getInterfaces().length); 
//NOT OK! Prints 0
System.out.println(WARNING.getClass().getInterfaces().length); 
È stato utile?

Soluzione

Use the following loop to understand:

public static void main(String[] args) {
    for (MyEnum e : MyEnum.values()) {
        System.out.println(e + ".getClass() = " + e.getClass());
    }
}

And it will print:

ERROR.getClass() = class com.stackoverflow.MyEnum
WARNING.getClass() = class com.stackoverflow.MyEnum$1
SUCCESS.getClass() = class com.stackoverflow.MyEnum

This means the WARNING is in fact an instance of an anonymous class, whhich extends MyEnum. And getInterfaces() only returns the interfaces that the class declaresto implement (i.e. the ones in the implements clause of the class declaration)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top