Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #25709

Re: limitations on using enum as generic parameter

From Daniele Futtorovic <da.futt.news@laposte.net.invalid>
Newsgroups comp.lang.java.programmer
Subject Re: limitations on using enum as generic parameter
Date 2011-02-08 19:35 +0100
Organization A noiseless patient Spider
Message-ID <iis2dp$qbs$1@news.eternal-september.org> (permalink)
References <76e9be77-f846-4559-82ec-1d774a8a6a0b@q36g2000yqn.googlegroups.com>

Show all headers | View raw


On 08/02/2011 18:50, dalamb@cs.queensu.ca allegedly wrote:
> I am playing around with using enums and generics together in Java 1.5
> (yes, I know it's in end-of-life, but it would be a bit of trouble
> right now to go to 1.6 let alone 1.7).  Having figured out some simple
> situations, I tried writing a generic class that takes an enum as a
> type parameter.  Unfortunately I don't seem to be able to invoke the
> enum's values() method -- javac says "Cannot find symbol: method
> values()".  (the reference to Enum.valueof later also gets errors,
> which is why I commented it out to simplify the test).
>
> Is there any way around this, or is there just no way to refer to an
> enum's values() method when the enum is a generic parameter?
>
> Here's the code; interface MessageCode should be irrelevant because it
> could be any old interface for the purposes of this example:
>
> public class EnumCodeSet<E extends Enum&  MessageCode>
> 				//    implements MessageCodeSet
> {
>      private E[] enums;
>      public EnumCodeSet() {
> 	enums = E.values();
>      }
>
>      public MessageCode get(int index)
> 	throws IndexOutOfBoundsException
>      {
> 	return enums[index];
>      } // get
>
>      public MessageCode valueOf(String name)
> 	throws IllegalArgumentException, NullPointerException
>      {
> 	// return Enum.valueof(E,name);
>      } //
> } // end class EnumCodeSet

HTH.

public class EnumCodeSet<E extends Enum<E> & MessageCode>
{
     private final Class<E> clazz;
     public EnumCodeSet( Class<E> clazz ) {
         if( clazz == null ) {
             throw new IllegalArgumentException( new 
NullPointerException() );
         }

         this.clazz = clazz;
     }

     public MessageCode get(int index)
	throws IndexOutOfBoundsException
     {
         return clazz.getEnumConstants()[ index ];
     } // get

     public MessageCode valueOf(String name)
	throws IllegalArgumentException, NullPointerException
     {
         return Enum.valueOf(clazz, name);
     } //
} // end class EnumCodeSet

Back to comp.lang.java.programmer | Previous | Next | Find similar


Thread

Re: limitations on using enum as generic parameter Daniele Futtorovic <da.futt.news@laposte.net.invalid> - 2011-02-08 19:35 +0100

csiph-web