枚举,用于开关盒
我有一个Enum定义,它包含方法返回类型,如“String”,Float,List,Double等。
我将在switch case语句中使用它。 例如,我的枚举是
public enum MethodType { DOUBLE,LIST,STRING,ARRAYLIST,FLOAT,LONG; }
在属性文件中,我的键值对如下。 Test1 = String Test2 = Double
在我的代码中,我得到了密钥的值。 我需要在Switch Case中使用VALUE来确定类型,并基于此我要实现一些逻辑。 例如像这样的东西
switch(MethodType.DOUBLE){ case DOUBLE: //Dobule logic }
有人可以帮我实现吗?
我想这就是你要找的东西:
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; } } }
为了不区分大小写,您可以执行MethodType.valueOf( value.toUpperCase() )
。
这可能会更接近您的需求。 在这种情况下,您可以将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); } }
您已经定义了枚举,但是您需要定义一个该类型的变量。 喜欢这个:
public enum MethodType { ... } public MethodType myMethod; switch (myMethod) { case MethodType.DOUBLE: //... break; case MethodType.LIST: //... break; //... }
编辑:
以前,此代码段使用var
作为变量名称,但这是一个保留关键字。 改为myMethod
。
你根本不需要一个开关(这是在java btw,所以可能不适合你):显然你会想要添加一些空检查,更好的exception处理等。
public enum MethodType { String,LONG,DOUBLE,THING; static MethodType fromString(String x) throws Exception { for (MethodType currentType: MethodType.values()){ if (x.equals(currentType.toString())){ return currentType; } } throw new Exception("Unmatched Type"); } }
- 如何使用JSESSIONID手动加载Java会话?
- 生成REST API的Swagger UI文档
- 将JProgressBar与Java Mail一起使用(知道transport.send()之后的进度)
- 如何从sql数据库获取日期数据类型到java?
- 在Custom JSP标记中传递Java对象值
- ArrayBlockingQueue使用单个锁进行插入和删除,但LinkedBlockingQueue使用2个单独的锁
- 从Spring Controller获取Web App根目录
- JPanel setBackground(Color.BLACK)什么都不做
- 如何检查java.lang.reflect.Type是否为Enum