user63904
user63904

Reputation:

Getting the values() of an enum when the enum is declared as a generic parameter

The code shown below does work because the method values() is static. My question is how can I achieve what the code below would do if B was not generic.

class A<B extends Enum<B>> {
    public A() {
        for (B b : b.values()) {

        }
    }
}

I can think of two solutions:

  1. pass the enum values into A's constructor
  2. make B implement an interface that defines a method for obtaining the enum values.

Both seem messy to me. Anyone have any better solutions?

Upvotes: 3

Views: 149

Answers (2)

Brad Mace
Brad Mace

Reputation: 27886

Here's a stripped-down example involving a subclass of JPanel that let's you choose a value from an Enum using radio buttons. To use it you'd do something like:

enum Animal { DOG, CAT, FISH };
RadioPanel<Animal> animal_panel = new RadioPanel<Animal>(Animal.class);
dialog.add(animal_panel);
...
Animal favorite_animal = animal_panel.getSelectedOption();

The class itself:

public class RadioPanel<T extends Enum<T>> extends JPanel {
    private Map<T,JRadioButton> buttons;
    private ButtonGroup button_group;
    private Class<T> clazz;

    public RadioPanel(Class<T> clazz) {
        this.clazz = clazz;
        buttons = new EnumMap<T, JRadioButton>(clazz);
        button_group = new ButtonGroup();       

        for (T value : clazz.getEnumConstants()) {
            JRadioButton button = new JRadioButton(value.toString());
            buttons.put(value, button);
            button_group.add(button);
            add(button);
        }
    }

    public void setSelectedOption(T value) {
        buttons.get(value).setSelected(true);
    }

    public T getSelectedOption() {
        for (T value : clazz.getEnumConstants()) {
            if (buttons.get(value).isSelected())
                return value;
        }

        return null;
    }
}

Upvotes: 1

Andy
Andy

Reputation: 8949

Try using getEnumConstants()

Upvotes: 7

Related Questions