Re: limitations on using enum as generic parameter
On Tue, 08 Feb 2011 09:50:32 -0800, dalamb@cs.queensu.ca wrote:
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?
public EnumCodeSet() {
enums = E.values();
}
That's not going to work. It's a static method of a class that isn't
determined at this point in the code, so the compiler simply has no clue
what to call. Hence the error message.
If you really need to do something like this, you'll need to use
reflection on a class object. Giving your class's constructors an added
Class<E> argument that gets stored in a type_token field and gets used
for reflection will work.
Reflection is slow, so the constructor should probably grab the values
and store them in an instance field. It looks like you were calling
values in your constructor anyway, so it turns from
public EnumCodeSet() {
enums = E.values();
}
to
public EnumCodeSet (Class<E> type_token) {
enums = type_token.getMethod("values").invoke(null);
}
Of course, when you make an EnumCodeSet you now have to pass the enum
class as a parameter to the constructor, e.g. new EnumCodeSet
(MyEnum.class).
You'll have to do something similar at the other site where you had an
error, or (better) store the reflectively-obtained result in an instance
field in the constructur and use the new instance field where you had the
error.