枚举,用于开关盒

App*_*pps 8 java enums

我有一个Enum定义,其中包含方法返回类型,如"String",Float,List,Double等.

我将在switch case语句中使用它.例如,我的枚举是

public enum MethodType {
    DOUBLE,LIST,STRING,ARRAYLIST,FLOAT,LONG;
}
Run Code Online (Sandbox Code Playgroud)

在属性文件中,我的键值对如下.Test1 = String Test2 = Double

在我的代码中,我得到了密钥的值.我需要在Switch Case中使用VALUE来确定类型,并基于此我要实现一些逻辑.例如像这样的东西

switch(MethodType.DOUBLE){
     case DOUBLE:
        //Dobule logic
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我实现吗?

tan*_*ens 23

我想这就是你要找的东西:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果不区分大小写,你可以做一个MethodType.valueOf( value.toUpperCase() ).


dig*_*tum 6

这可能会更接近您的需求.在这种情况下,您可以将propertyName属性设置为您需要的任何属性:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)


JYe*_*ton 5

你定义的枚举,但你需要定义一个变量就是这种类型.像这样:

public enum MethodType { ... }

public MethodType myMethod;

switch (myMethod)
{
    case MethodType.DOUBLE:
        //...
        break;
    case MethodType.LIST:
        //...
        break;
//...
}
Run Code Online (Sandbox Code Playgroud)

编辑:

以前,此片段用作var变量名称,但这是一个保留关键字.改为myMethod.