java Java1.6中的字符串切换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14496678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Switch with string in Java1.6
提问by Stefan Strooves
Possible Duplicate:
Switch Statement with Strings in Java
可能的重复:
Java 中带有字符串的 Switch 语句
Im using the following code and I wonder if there is a way to do it with switch , the reason that I don't use it as default since type name is type string.(I know that this option is supported in 1.7 version but I need to use 1.6) There is a way to overcome this problem ?
我使用下面的代码,我想知道是否有办法用 switch 做到这一点,我不使用它作为默认值的原因,因为类型名称是类型字符串。(我知道 1.7 版本支持此选项,但我需要使用 1.6) 有办法克服这个问题吗?
public static SwitchInputType<?> switchInput(String typeName) {
if (typeName.equals("Binary")) {
return new SwitchInputType<Byte>(new Byte("23ABFF"));
}
else if (typeName.equals("Decimal")) {
return new SwitchInputType<BigDecimal>(new BigDecimal("A"));
}
else if (typeName.equals("Boolean")) {
return new SwitchInputType<Boolean>(new Boolean("true"));
采纳答案by davioooh
As explained in other answers, you can't use switch statement with strings if you're working with Java 1.6.
如其他答案中所述,如果您使用的是 Java 1.6,则不能将 switch 语句与字符串一起使用。
The best thing to do is to use an enumerator instead of string values:
最好的办法是使用枚举器而不是字符串值:
public static SwitchInputType<?> switchInput(InputType type) {
switch(type){
BINARY:
return new SwitchInputType<Byte>(new Byte("23ABFF"));
DECIMAL:
return new SwitchInputType<BigDecimal>(new BigDecimal("A"));
BOOLEAN:
return new SwitchInputType<Boolean>(new Boolean("true"));
}
}
where:
在哪里:
public enum InputType{
BINARY, DECIMAL, BOOLEAN // etc.
}
UPDATE:
更新:
In your Field
class add an InputType fieldType
property. Then inside the loop:
在您的Field
课程中添加一个InputType fieldType
属性。然后在循环内:
MemberTypeRouting.switchInput(field.getFieldType());
回答by sonOfRa
Switches with Strings are only supported since Java 7. Sadly it was not supported in older versions, so you cannot use it wit Java 6, and you'll have to stay with the if/else statements you are already using.
从 Java 7 开始只支持带字符串的开关。遗憾的是,旧版本不支持它,所以你不能在 Java 6 中使用它,你必须继续使用你已经使用的 if/else 语句。
See also this question, asked a few years back: Why can't I switch on a String?
另请参阅几年前提出的这个问题: 为什么我不能打开字符串?