Reputation: 71008
I have a generic type that is parameterized on some Enum, declared like this:
public class FlagsField<T extends Enum<T>> {
private EnumSet<T> _flagSet;
public FlagsField() {
_flagSet = EnumSet.<T>noneOf( /* what goes here? */ );
}
...
}
I want to initialize _flagsField in the constructor as above, but can't figure out for the life of me what the right parameter to the noneOf method is. It needs to be of type Class<T>
. If this weren't a generic, you'd use MyFooEnumType.class
here, but T.class
is not valid.
Thanks!
Upvotes: 0
Views: 1437
Reputation: 13906
You could use this trick in your constructor: (see Generic Data Access Objects, section "Preparing DAOs with lookup")
enumClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
But I believe this code only works when the class is sub-classed and an instance of the sub-class executes it.
Upvotes: 2
Reputation: 21628
You've run into type erasure. Your constructor is going to need to look like:
public FlagsField(Class<T> enumClass) {
_flagSet = EnumSet.<T>noneOf(enumClass);
}
Upvotes: 9