原文同步至 http://www.waylau.com/java-switch-use-string/
当我尝试在 switch 语句使用 String 参数时(注意ctrType为字符串)
<!-- more -->1 switch (ctrType) { 2 case "01" : 3 exceptionType = "读FC参数数据"; 4 break; 5 case "03" : 6 exceptionType = "读FC保存的当前表计数据"; 7 break; 8 default: 9 exceptionType = "未知控制码:"+ctrType; 10 }
提示如下错误:
Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted
意思是说,我的 jre 本版本太低,不支持。据查 在 Java 7之前,switch 只能支持 byte、short、char、int或者其对应的封装类以及 Enum 类型。在 Java 7中,String支持也终于被加上了。
解决
普通项目
安装 JDK 1.7+,在项目中更改配置引入该 JDK 版本依赖库。
Maven 项目
更改 pom.xml 文件,设置 maven-compiler-plugin 插件目标版本为 1.7+,例如
1 <plugins> 2 ... 3 <plugin> 4 <groupId>org.apache.maven.plugins</groupId> 5 <artifactId>maven-compiler-plugin</artifactId> 6 <version>3.2</version> 7 <configuration> 8 <source>1.7</source> 9 <target>1.7</target> 10 </configuration> 11 </plugin> 12 ... 13 </plugins>