转载请注明原文链接。
http://zhaorui1125.iteye.com/blog/2264969
直接贴代码。
标签处理Java代码:
import java.lang.reflect.Field;
/**
* @date 2015年12月18日 上午10:26:33
*/
public class EnumTag {
/**
* 根据类名、枚举名、字段名获取枚举值
* @param className
* @param enumName
* @param fieldName
* @return
* @throws NoSuchFieldException
* @throws SecurityException
* @throws ClassNotFoundException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static<T> T getEnumValue(String className,String enumName,String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException{
Class c = Class.forName(className);
Field f = c.getField(enumName);
Object o =f.get(c);
Field f1 = o.getClass().getDeclaredField(fieldName);
f1.setAccessible(true);
return (T)f1.get(o);
}
public static Integer getInt(String className,String enumName,String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException{
return getEnumValue(className,enumName,fieldName);
}
public static String getStr(String className,String enumName,String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException{
return getEnumValue(className,enumName,fieldName);
}
}
配置文件:
<?xml version="1.0" encoding="GB2312" ?> <taglib xmlns=" http://java.sun.com/xml/ns/j2ee" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>get enum value tld</description> <display-name>enum</display-name> <tlib-version>1.0</tlib-version> <short-name>enum</short-name> <uri>/enum</uri> <function> <description>获取枚举值</description> <name>getStr</name> <function-class>com.mtime.b2c.tags.EnumTag</function-class> <function-signature>java.lang.String getStr(java.lang.String,java.lang.String,java.lang.String)</function-signature> </function> <function> <description>获取枚举值</description> <name>getInt</name> <function-class>com.mtime.b2c.tags.EnumTag</function-class> <function-signature>java.lang.Integer getInt(java.lang.String,java.lang.String,java.lang.String)</function-signature> </function> </taglib>
标签使用
<%@ taglib prefix="img" uri="/img"%>
${enum:getInt('com.xxx.b2c.constant.GoodsContentLayoutEnum','Text','value')}