Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums,use in switch case

Tags:

java

enums

I have an Enum defined which contains method return type like "String",Float,List,Double etc.

I will be using it in switch case statements. For example my enum is

public enum MethodType {
    DOUBLE,LIST,STRING,ARRAYLIST,FLOAT,LONG;
}

In a property file, I've key value pairs as follows. Test1=String Test2=Double

In my code I'm getting the value for the key. I need to use the VALUE in Switch Case to Determine the Type and based on that I've to implement some logic. For example something like this

switch(MethodType.DOUBLE){
     case DOUBLE:
        //Dobule logic
}

Can someone please help me to implement this?

like image 372
Apps Avatar asked May 14 '10 17:05

Apps


2 Answers

I guess this is what you are looking for:

public class C_EnumTest {
    public enum MethodType {
        DOUBLE,LIST,STRING,ARRAYLIST,FLOAT,LONG;
    }
    public static void main( String[] args ) {
        String value = "DOUBLE";
        switch( MethodType.valueOf( value ) ) {
        case DOUBLE:
            System.out.println( "It's a double" );
            break;
        case LIST:
            System.out.println( "It's a list" );
            break;
        }
    }
}

For not being case sensitive you could do a MethodType.valueOf( value.toUpperCase() ).

like image 134
tangens Avatar answered Oct 06 '22 22:10

tangens


This may be a little closer to what you need. You can make the propertyName property anything you need it to be in this case:

public enum MethodType {

  STRING("String"),
  LONG("Long"),
  DOUBLE("Double"),
  THING("Thing");

  private String propertyName;

  MethodType(String propName) {
    this.propertyName = propName;
  }

  public String getPropertyName() {
    return propertyName;
  }

  static MethodType fromPropertyName(String x) throws Exception {
    for (MethodType currentType : MethodType.values()) {
      if (x.equals(currentType.getPropertyName())) {
        return currentType;
      }
    }
    throw new Exception("Unmatched Type: " + x);
  }
}
like image 27
digitalsanctum Avatar answered Oct 07 '22 00:10

digitalsanctum