4

Is it possible to let a enum in java take a set of enums as as argument? If yes, then how do I implement it?

When using this I whant to be able to say something like: Take a MODAL_SETTINGS.EDIT_MODAL_WINDOW and create this with the buttons MODAL_BUTTONS.SAVE & MODAL_BUTTONS.CANCEL.

This is what I have as of now

public enum MODAL_SETTINGS {
    NEW_MODAL_WINDOW(MODAL_BUTTONS.class),
    EDIT_MODAL_WINDOW(MODAL_BUTTONS.class),
    DELETE_MODAL_WINDOW(MODAL_BUTTONS.class);

    private EnumSet buttons;

    private MODAL_SETTINGS(EnumSet<MODAL_BUTTONS> buttons){

    }

}
public enum MODAL_BUTTONS {
    SAVE, UPDATE, CANCEL, DELETE
}
1
  • 1
    This isn't really relevant, but the normal naming convention for classes (including enum types) is to use CamelCase (even though the enum constants themselves use UPPER_CASE). Commented Jun 29, 2011 at 23:58

3 Answers 3

12

Instead of this:

NEW_MODAL_WINDOW(MODAL_BUTTONS.class),

I suspect you want this:

NEW_MODAL_WINDOW(EnumSet.allOf(MODAL_BUTTONS.class))

or

NEW_MODAL_WINDOW(EnumSet.of(MODAL_BUTTONS.SAVE, MODAL_BUTTONS.CANCEL))

(etc).

Otherwise you're just passing a Class<T>, not an EnumSet.

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

Comments

10

No problem:

enum Color {YELLOW, BLUE, GREEN}

enum Environment { 
     SUN(Color.YELLOW), OCEAN(Color.BLUE), TREE(Color.GREEN);

     private Color color;
     private Environment(Color color) {
       this.color = color;
     }
     public Color getColor() {
       return color;
     }
}

Comments

3

Yes, look at this:

import java.util.EnumSet;
public class EnumTest {
public static enum MODAL_BUTTONS {
    SAVE, UPDATE, CANCEL, DELETE
}
public static enum MODAL_SETTINGS {
    NEW_MODAL_WINDOW(EnumSet.of(MODAL_BUTTONS.SAVE, MODAL_BUTTONS.UPDATE)),
    EDIT_MODAL_WINDOW(EnumSet.of(MODAL_BUTTONS.UPDATE, MODAL_BUTTONS.CANCEL)),
    DELETE_MODAL_WINDOW(EnumSet.of(MODAL_BUTTONS.CANCEL, MODAL_BUTTONS.DELETE));

    private EnumSet<MODAL_BUTTONS> buttons;

    MODAL_SETTINGS(EnumSet<MODAL_BUTTONS> buttons){
        this.buttons = buttons;
    }
    EnumSet<MODAL_BUTTONS> getBtns() {
        return this.buttons;
    }
}
    public static void main(String... args) {
        System.out.println(MODAL_SETTINGS.NEW_MODAL_WINDOW.getBtns());
        System.out.println(MODAL_SETTINGS.EDIT_MODAL_WINDOW.getBtns());
        System.out.println(MODAL_SETTINGS.DELETE_MODAL_WINDOW.getBtns());
   }
}

The output is:

[SAVE, UPDATE]
[UPDATE, CANCEL]
[CANCEL, DELETE]

Comments

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.