How to call implemented method of generic enum in Java?

Posted by Justin Wiseman on Stack Overflow See other posts from Stack Overflow or by Justin Wiseman
Published on 2012-12-02T22:51:42Z Indexed on 2012/12/02 23:03 UTC
Read the original article Hit count: 224

Filed under:
|
|
|
|

I am trying pass an enum into a method, iterate over that enums values, and call the method that that enum implements on all of those values. I am getting compiler errors on the part "value.getAlias()". It says "The method getAlias() is undefined for the type E" I have attempted to indicate that E implements the HasAlias interface, but it does not seem to work. Is this possible, and if so, how do I fix the code below to do what I want? The code below is only meant to show my process, it is not my intention to just print the names of the values in an enum, but to demonstate my problem.

public interface HasAlias{ String getAlias(); };

public enum Letters implements HasAlias
{
   A("The letter A"),
   B("The letter B");

   private final String alias;

   public String getAlias(){return alias;}

   public Letters(String alias)
   {
     this.alias = alias;
   }

}

public enum Numbers implements HasAlias
{
   ONE("The number one"),
   TWO("The number two");

   private final String alias;

   public String getAlias(){return alias;}

   public Letters(String alias)
   {
     this.alias = alias;
   }

}

public class Identifier
{
   public <E extends Enum<? extends HasAlias>> void identify(Class<E> enumClass)
   {
      for(E value : enumClass.getEnumConstants())
      {
         System.out.println(value.getAlias());
      }
   }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about generics