Fw: Generics in enums

Joe Darcy joe.darcy at oracle.com
Thu May 30 06:43:59 UTC 2013


Hello Victor,

On 5/29/2013 11:25 PM, Victor Polischuk wrote:
> Greetings,
>
> I beg pardon for the previous HTML mail.
>
> Some time ago I wanted to migrate our "commons-lang" enums to "java 5" enumerations, but I encountered an issue that it cannot be done without discarding generics since java enums do not support them. Let me show an example:
>
> //------
> public final class ColorEnum<T extends Pixel> extends org.apache.commons.lang.enums.Enum {
>      public static final ColorEnum<PurePixel> RED = new ColorEnum<PurePixel>("Red");
>      public static final ColorEnum<PurePixel> GREEN = new ColorEnum<PurePixel>("Green");
>      public static final ColorEnum<PurePixel>�BLUE = new ColorEnum<PurePixel>("Blue");
>      public static final ColorEnum<MixedPixel> WHITE = new ColorEnum<MixedPixel>("White") {
>          @Override
>          public MixedPixel make() {...}�
>      };
>      
>      private ColorEnum(String color) {super(color);}
>      
>      public boolean filter(T pixel) {...}
>      
>      public T make() {...}
> }
> //------
>
> And I wonder if there is a specific reason why I cannot convert it into something like:�
>
> //------
> public enum Color<T extends Pixel> {
>      RED<PurePixel>("Red"),
>      GREEN<PurePixel>("Green"),
>      BLUE<PurePixel>("Blue"),
>      WHITE<MixedPixel>("White") {
>          @Override
>          public MixedPixel make() {...}�
>      };
>
>      private Color(String color) {...}
>
>      public boolean filter(T pixel) {...}
>
>      public T make() {...}
> }
> //------
>
> Thank you in advance.
>
> Sincerely yours,
> Victor Polischuk

You can approximate this effect by having your enum implement an 
interface or even a generic interface. For some examples in the JDK see, 
javax.tools.StandardLocation and java.nio.file.LinkOption.

HTH,

-Joe



More information about the core-libs-dev mailing list