IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]struts2的action支持自动转换枚举类型(enum)的实例变量

    wangjian5748发表于 2011-09-16 17:03:10
    love 0

    今天看到很多程序员写的代码,老是在enum与string之间来回转换,自己也不确定struts2能否进行enum的类型转换,struts2的文档说不支持enum的自动转换,通过阅读struts2的DefaultTypeConverter源代码发现是可以的,主要集中在convertValue方法

        public Object convertValue(Object value, Class toType) {
            Object result = null;
    
            if (value != null) {
                /* If array -> array then convert components of array individually */
                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)toType, value);
                }
            } else {
                if (toType.isPrimitive()) {
                    result = primitiveDefaults.get(toType);
                }
            }
            return result;
        }




沪ICP备19023445号-2号
友情链接