在实际的项目开发中,反射操作类的实例、属性赋值、执行方法是常规的操作,虽然spring提供了比较完整的API来执行上述操作,不过在实际的应用中,spring的函数隐藏比较深,比较分散,小伙伴们可能懒得花时间去寻找。本类集成了一些常规操作,值得收藏,请关注展翅,展翅会定时更新有项目实战价值的代码和技术。
import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import net.sf.json.JsonConfig;import org.apache.commons.beanutils.PropertyUtils;import org.springframework.util.ObjectUtils;import com.esotericsoftware.reflectasm.MethodAccess;import com.ivt.monitor.utils.common.CommonUtils;import com.ivt.monitor.utils.common.StringUtil;public class ReflectASMUtils {/** * Class,MethodAccess的缓存map */private static Map, MethodAccess> classMethodAccessMap;static{classMethodAccessMap = new HashMap, MethodAccess>();}/** * 根据字段名获取对应的bean的值
* 为了避免因为bean的set,get不规范而出异常,加上PropertyUtils.getProperty(bean, field); * @param bean * @param field * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */public static Object getProperty(Object bean, String field) throws IllegalAccessException,InvocationTargetException, NoSuchMethodException{try{Class> clazz = bean.getClass(); String methodName = "get".concat(field.substring(0, 1).toUpperCase().concat(field.substring(1, field.length())));MethodAccess access = getCacheMethodAccess(clazz);Object obj = access.invoke(bean, methodName);/*if(obj != null && obj instanceof Date){obj = CommonUtils.getDateString((Date) obj);}*/return obj;}catch (Exception e) {return PropertyUtils.getProperty(bean, field);}}/** * 根据字段名为bean设置对应的值
* 为了避免因为bean的set,get不规范而出异常,加上PropertyUtils.setProperty(bean, field, value); * @param bean * @param field * @param value * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */public static void setProperty(Object bean, String field, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{try{Class> clazz = bean.getClass(); String methodName = "set".concat(field.substring(0, 1).toUpperCase().concat(field.substring(1, field.length())));MethodAccess access = getCacheMethodAccess(clazz);access.invoke(bean, methodName, value);}catch (Exception e) {PropertyUtils.setProperty(bean, field, value);}}/** * map返回成一个bean * @param clazz * @param map * @return */public static T setBeanValue(Class clazz, Map map){try{T bean = clazz.newInstance();if(bean == null || CommonUtils.isCollectionEmpty(map)){return null;}Set keys = map.keySet();for(String field : keys){String methodName = "set".concat(field.substring(0, 1).toUpperCase().concat(field.substring(1, field.length())));MethodAccess access = getCacheMethodAccess(clazz);access.invoke(bean, methodName, map.get(field));}return bean;}catch(Exception e){return null;}}/** * mapList返回成一个bean list * @param clazz * @param mapList * @return */public static List setBeanListValue(Class clazz, List> mapList){if(clazz == null || CommonUtils.isCollectionEmpty(mapList)){return null;}List list = new ArrayList();for(Map map : mapList){list.add(setBeanValue(clazz, map));}return list;}/** * 获取bean所有字段的json * @param bean * @return */public static JSONObject getBeanJSONObjectByField(Object bean){JSONObject json = new JSONObject();List fieldList = getFieldNameList(bean);if(CommonUtils.isCollectionEmpty(fieldList)){return json;}Object obj = null;for(String field : fieldList){try {obj = getProperty(bean, field);} catch (Exception e) {} json.put(field, obj);}return json;}/** * app获取bean所有字段的json * @param bean * @return */public static JSONObject getBeanJSONObjectByFieldForApp(Object bean){/*Gson gson = new GsonBuilder().serializeNulls().create();String gsonString = gson.toJson(bean);return JSONObject.fromObject(gsonString);*/JSONObject json = new JSONObject();List fieldList = getFieldNameList(bean);if(CommonUtils.isCollectionEmpty(fieldList)){return json;}Object obj = null;for(String field : fieldList){try {obj = getPropertyForApp(bean, field);} catch (Exception e) {} json.put(field, obj);}return json;}/** * 根据JsonConfig,获取bean指定字段的json * @param bean * @param config * @param fields * @return */public static JSONObject getBeanJSONObjectByField(Object bean, JsonConfig config, String ... fields){JSONObject json = JSONObject.fromObject(bean, config);if(CommonUtils.isCollectionEmpty(fields)){return json;}JSONObject retJson = new JSONObject();Object obj = null;for(String field : fields){obj = json.get(field);retJson.put(field, obj);}return retJson;}/** * 获取bean指定字段的json * @param bean * @param fields * @return */public static JSONObject getBeanJSONObjectByField(Object bean, String ... fields){JSONObject json = new JSONObject();if(CommonUtils.isCollectionEmpty(fields)){return json;}Object obj = null;for(String field : fields){try {obj = getProperty(bean, field);} catch (Exception e) {} json.put(field, obj);}return json;}/** * 获取bean所有的get方法的json,key为对应的生成的字段 * @param bean * @return */public static JSONObject getBeanJSONObjectByMethod(Object bean){JSONObject json = new JSONObject();List getMethodList = getGetMethodNameList(bean);if(CommonUtils.isCollectionEmpty(getMethodList)){return json;}Class> clazz = bean.getClass();String key = "";String value = "";MethodAccess access = null;Object obj = null;for(String methodName : getMethodList){key = methodName.substring(3, 4).toLowerCase().concat(methodName.substring(4, methodName.length()));if(StringUtil.isStrEmpty(key)){continue;}access = getCacheMethodAccess(clazz);obj = access.invoke(bean, methodName);if(obj != null && obj instanceof Date){value = StringUtil.getDateString((Date) obj); //除了日期,其他都利用spring的帮助类}else{value = ObjectUtils.getDisplayString(obj); //利用spring的帮助类}json.put(key, value);}return json;}/** * 给JSONObject对应的值增加前缀 * @param json * @param map * @return */public static JSONObject setUpPrefix(JSONObject json, Map map){if(CommonUtils.isCollectionEmpty(map)){return json;}Set keys = map.keySet();Object value = null;for(String key : keys){value = json.get(key);if(value != null && !"".equals(value.toString())){json.put(key, map.get(key) + value);}}return json;}///** * 根据JsonConfig,获取bean list指定字段的JSONArray * @param beanList * @param config * @param fields * @return */public static JSONArray getBeanListJSONArrayByField(List> beanList, JsonConfig config, String ... fields){JSONArray array = new JSONArray();if(CommonUtils.isCollectionEmpty(beanList) || CommonUtils.isCollectionEmpty(fields)){return array;}for(Object bean : beanList){array.add(getBeanJSONObjectByField(bean, config, fields));}return array;}/** * 获取bean list 的JSON数组 * @param beanList * @param fields * @return */public static JSONArray getBeanListJSONArray(List> beanList){JSONArray array = new JSONArray();if(CommonUtils.isCollectionEmpty(beanList)){return array;}for(Object bean : beanList){array.add(JSONObject.fromObject(bean));}return array;}/** * 获取bean list指定字段的JSONArray * @param beanList * @param fields * @return */public static JSONArray getBeanListJSONArrayByField(List> beanList, String ... fields){JSONArray array = new JSONArray();if(CommonUtils.isCollectionEmpty(beanList) || CommonUtils.isCollectionEmpty(fields)){return array;}for(Object bean : beanList){array.add(getBeanJSONObjectByField(bean, fields));}return array;}/** * app获取bean list指定字段的JSONArray * @param beanList * @param fields * @return */public static JSONArray getBeanListJSONArrayByFieldForApp(List> beanList, String ... fields){JSONArray array = new JSONArray();if(CommonUtils.isCollectionEmpty(beanList) || CommonUtils.isCollectionEmpty(fields)){return array;}for(Object bean : beanList){array.add(getBeanJSONObjectByFieldForApp(bean, fields));}return array;}/** * 获取bean list所有的get方法的JSONArray * @param beanList * @return */public static JSONArray getBeanListJSONArrayByMethod(List> beanList){JSONArray array = new JSONArray();if(CommonUtils.isCollectionEmpty(beanList)){return array;}for(Object bean : beanList){array.add(getBeanJSONObjectByField(bean));}return array;}/** * 给JSONArray对应的值增加前缀 * @param array * @param map * @return */public static JSONArray setUpPrefix(JSONArray array, Map map){if(CommonUtils.isCollectionEmpty(map)){return array;}int size = array.size();if(size <= 0){return array;}JSONObject json = null;for(int i=0; i getFieldNameList(Object bean){Class> clazz = bean.getClass();Field[] implFs = clazz.getDeclaredFields(); //实现类,也就是本身的字段List fieldNameList = new ArrayList();String name = "";for(Field fs : implFs){name = fs.getName();if(("serialVersionUID").equalsIgnoreCase(name))continue;fieldNameList.add(name);}return fieldNameList;}/** * 获取所有的方法 * @param name * @return */private static List getGetMethodNameList(Object bean){List getMethodList = new ArrayList();Class> clazz = bean.getClass();Method[] mds = clazz.getMethods();String name = null;for(Method md : mds){name = md.getName();if(name.startsWith("get") && !"getClass".equalsIgnoreCase(name)){getMethodList.add(name);}}return getMethodList;}/** * 因为MethodAccess.get(clazz);比较耗时,所以缓存起来 * @param clazz * @return */private static MethodAccess getCacheMethodAccess(Class> clazz){MethodAccess obj = classMethodAccessMap.get(clazz);if(obj == null){MethodAccess access = MethodAccess.get(clazz);classMethodAccessMap.put(clazz, access);return access;}return obj;}/** * 获取bean指定字段的json * @param bean * @param fields * @return */public static JSONObject getBeanJSONObjectByFieldForApp(Object bean, String ... fields){JSONObject json = new JSONObject();if(CommonUtils.isCollectionEmpty(fields)){return json;}Object obj = null;for(String field : fields){try {obj = getPropertyForApp(bean, field);} catch (Exception e) {} json.put(field, obj);}return json;}/** * app的日期返回long * @param bean * @param field * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */private static Object getPropertyForApp(Object bean, String field) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{try{Class> clazz = bean.getClass(); String methodName = "get".concat(field.substring(0, 1).toUpperCase().concat(field.substring(1, field.length())));MethodAccess access = getCacheMethodAccess(clazz);Object obj = access.invoke(bean, methodName);if(obj != null && obj instanceof java.util.Date){obj = new Long(((Date) obj).getTime());}if(obj == null){//获取字段的类型Field _field = clazz.getDeclaredField(field); Class> fieldType = _field.getType(); if(fieldType == Number.class || fieldType.getSuperclass() == Number.class || fieldType == java.util.Date.class || fieldType == java.sql.Date.class){ obj = 0; }else{ obj = ""; }}return obj;}catch (Exception e) {return PropertyUtils.getProperty(bean, field);}}}