Reputation: 3775
Hi I'm trying to provide an enum to a generic class so I can iterate over the a set of members defined by the supplied Enum type parameter. I found a way to do this, but in order for it to work, I need to supply an arbitrary instance of the enum.
public enum suits {
spades,
hearts,
diamonds,
clubs;
}
public static class Card<E extends Enum<E>> {
public final EnumSet<E> suits;
public Card(E instance) {
EnumSet<E> mySet = EnumSet.allOf(instance.getDeclaringClass());
this.suits = mySet;
}
}
Now I can do something like this:
Card<Suits> myCard = new Card<Suits>(Suits.clubs);
String names = "";
for (Suit s : myCard.suits) {names += s.name + "|";} // "spades|hears|diamonds|clubs|
Here is the question: Can I do this without supplying an instance of the enum in the Card object constructor?
What I would think ought to work is to replace instance.getDeclaringClass() with the type parameter when creating the enum, as in:
EnumSet<E> mySet = EnumSet.allOf(E);
but that gives a syntax error. Somehow it seems like it should be possible to get type type parameter without having to resort to supplying an enum instance and then calling getDeclaringClass().
Upvotes: 0
Views: 50
Reputation: 198033
You can pass in Suits.class
, but you need one or the other -- either an instance of the enum type, or a Class
object for the enum type.
Upvotes: 1