您的位置:首页 > 编程语言 > Java开发

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

2011-09-16 17:03 375 查看
今天看到很多程序员写的代码,老是在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<Enum>)toType, value);
}
} else {
if (toType.isPrimitive()) {
result = primitiveDefaults.get(toType);
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息