3

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

2 回答 2

3

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());
于 2013-01-24T08:36:57.677 回答
2

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?

于 2013-01-24T08:20:56.667 回答