Switch with string in Java1.6

Possible Duplicate:
Switch Statement with Strings in Java

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 ?

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"));

As explained in other answers, you can't use switch statement with strings if you're working with Java 1.6.

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:

MemberTypeRouting.switchInput(field.getFieldType());

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.

See also this question, asked a few years back: Why can't I switch on a String?

链接地址: http://www.djcxy.com/p/84510.html

上一篇: 为什么这是交换(Java)发生的?

下一篇: 在Java1.6中用字符串切换