| Author |
generic enum and the values() method
|
john q bovis
Greenhorn
Joined: Feb 09, 2011
Posts: 1
|
|
Hi,
Was playing with some generics and java's enums earlier and can't figure out why the code below gives me a compile error about the 'values()' method call.
It's saying that :-
the method values() is undefined for the type E
But I thought since a java enum implicitly extends Enum and values() is a static method given by using an enum type, there's no reason the below wouldn't work (as I've stated that E is extending Enum). Anybody have any suggestions or have any reason why it's giving me that error?
Note : Interestingly I did take a look at the Java API (1.6) and it looks like Enum doesn't actually have the values() method specified??? So if this is the case where does a java enum get the values() method from (so should my extends be extending that?) or is it some real trickery done by the compiler (thus the code below cannot be fixed?). I did notice that if I use any of the methods from the Enum Api declarations, they compile)
Any help would be much appreciated.
Ps. Before anybody comments, I know the below code isn't really logical since I could use valueOf(...) to do the same but its meant as an illustrative example of what I'm really doing so please don't comment on that and only post if you have something about my actual question.
|
 |
Leonardo Shikida
Greenhorn
Joined: Jan 02, 2003
Posts: 29
|
|
Strange, isn“t it?
try this
what Oracle says
http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.
so, maybe you're right. Maybe, this method does not exist BEFORE compiling time.
I hope it helps
Leo K.
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3056
|
|
values() is not a method of Enum. It's a method that is implicitly added by the compiler to the enum subclass you define.
Therefore, if you use Enum as a bound on your generic parameter, it won't be specific enough for you to call the values() method.
|
 |
 |
|
|
subject: generic enum and the values() method
|
|
|