-1
public class TestingGen {

    /**
     * @param args
     */

    public enum Types {

        TYPE1("TYPE1"), TYPE2("TYPE2");

        private String type;

        private Types(String type) {
            this.type = type;
        }

        public String getType() {
            return type;
        }
    }

    public static void main(String[] args) {

        String value = null;
        switch (value) {
        case Types.TYPE1.getType():
            System.out.println("here");
            break;
        case Types.TYPE2.getType():
            System.out.println("there");
        default:
            System.out.println("default");
        }
    }

}

Its showing errors on both the case statements "case expressions must be constant expressions".

How can I use String enums in swtich statement then ?

Vineet Singla
  • 1,609
  • 2
  • 20
  • 34

2 Answers2

2

The other way around. Get the enum value for your string Types enumValue = Types.valueOf(stringValue) and switch on the enum values switch(enumValue) { case TYPE1: [...].

duckstep
  • 1,148
  • 8
  • 17
-1

public class TestingGen {

/**
 * @param args
 */

public enum Types {

    TYPE1("TYPE1"), TYPE2("TYPE2");
     String type = null;

    Types(String s) {
        type = s;
    }

     String getType() {
        return type;
    }
}

public static void main(String[] args) {

    for(Types value : Types.values()) { 
        System.out.println(value + "  " + value.getType() + " ");
     }

}

}

ajay
  • 477
  • 6
  • 14