0

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().

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So there is no way to either derive an instance or a Class object from a type parameter that is scoped to an enum type.
Nope. Generics don't exist at runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.