2025-02-10

今天看到很多程序員寫的代碼,老是在enum與string之間來回轉換,自己也不確定struts2能否進行enum的類型轉換,struts2的文檔說不支持enum的自動轉換,通過閱讀struts2的DefaultTypeConverter源代碼發現是可以的,主要集中在convertValue方法

view plaincopy to clipboardprint?public Object convertValue(Object value, Class toType) { 
    Object result = null; 
 
    if (value != null) { 
        /* If array -> array then convert components of array inpidually */ 
        if (value.getClass().isArray() && toType.isArray()) { 
            Class componentType = toType.getComponentType(); 
 
            result = Array.newInstance(componentType, Array 
                    .getLength(value)); 
            for (int i = 0, icount = Array.getLength(value); i < icount; i++) { 
                Array.set(result, i, convertValue(Array.get(value, i), 
                        componentType)); 
            } 
        } else { 
            if ((toType == Integer.class) || (toType == Integer.TYPE)) 
                result = Integer.valueOf((int) longValue(value)); 
            if ((toType == Double.class) || (toType == Double.TYPE)) 
                result = new Double(doubleValue(value)); 
            if ((toType == Boolean.class) || (toType == Boolean.TYPE)) 
                result = booleanValue(value) ? Boolean.TRUE : Boolean.FALSE; 
            if ((toType == Byte.class) || (toType == Byte.TYPE)) 
                result = Byte.valueOf((byte) longValue(value)); 
            if ((toType == Character.class) || (toType == Character.TYPE)) 
                result = new Character((char) longValue(value)); 
            if ((toType == Short.class) || (toType == Short.TYPE)) 
                result = Short.valueOf((short) longValue(value)); 
            if ((toType == Long.class) || (toType == Long.TYPE)) 
                result = Long.valueOf(longValue(value)); 
            if ((toType == Float.class) || (toType == Float.TYPE)) 
                result = new Float(doubleValue(value)); 
            if (toType == BigInteger.class) 
                result = bigIntValue(value); 
            if (toType == BigDecimal.class) 
                result = bigDecValue(value); 
            if (toType == String.class) 
                result = stringValue(value); 
            if (Enum.class.isAssignableFrom(toType)) 
                result = enumValue((Class<Enum>)toType, value); 
        } 
    } else { 
        if (toType.isPrimitive()) { 
            result = primitiveDefaults.get(toType); 
        } 
    } 
    return result; 

 作者“'一界'書生”

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *