switch for type string for java 1.6

This question already has an answer here:

  • Why can't I switch on a String? 14 answers

  • 你甚至可以让enum为你做:

    public static void main(String[] args) throws InterruptedException {
        String typeName = "Boolean";
        String memberValue = "memberValue";
        SwitchInputType type = Type.valueOf(typeName).makeType(memberValue);
    }
    
    enum Type {
        Boolean {
            SwitchInputType makeType(String memberValue) {
                return new SwitchInputType<Boolean>(new Boolean(memberValue));
            }
        },
        Double {
            SwitchInputType makeType(String memberValue) {
                return new SwitchInputType<Double>(new Double(memberValue));
            }
        }, 
        Int32 {
            SwitchInputType makeType(String memberValue) {
                return new SwitchInputType<Integer>(new Integer(memberValue));
            }
        };
    
        // All must do this.
        abstract SwitchInputType makeType(String memberValue);
    }
    
    static class SwitchInputType<T> {
        public SwitchInputType(Object o) {
        }
    }
    

    As your strings are all valid identifiers, you could create an enumeration with those strings as the item labels, use Enum.valueOf(Class, String) (or the similar valueOf(String) method that will be created in your enumeration class) to convert to a member of the enumeration type, and then switch based on that...

    Example:

    enum TypeName { Boolean, Double, Int32 }
    
    switch (TypeName.valueOf(typeName)) {
       case Boolean: // ...
       case Double: // ...
       case Int32: // ...
    }
    

    Ankur has already suggested one way. The other way is define these as constants. Ex - private static final String BOOLEAN = "1";

    switch(Integer.parseInt(BOOLEAN)) case 1:...

    case 2: ...

    and so on.

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

    上一篇: 字符串作为switch语句

    下一篇: 切换为java 1.6的字符串类型