反射工具类ReflectionUtils
生活随笔
收集整理的這篇文章主要介紹了
反射工具类ReflectionUtils
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
package net.pm.common.toolkit;import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.HashMap; import java.util.Map;import net.pm.core.entities.db.Pmdept; import net.pm.core.entities.db.Pmuser;import org.apache.commons.lang3.StringUtils;/**反射工具類* @author shizeyuan**/ public abstract class ReflectionUtils {/*** 緩存方法*/private static final Map<Class<?>, Method[]> METHODS_CACHEMAP = new HashMap<Class<?>, Method[]>();/*** 反射 取值、設值,合并兩個對象(Field same only )* * @param from* @param to*/public static <T> void copyProperties(T fromobj, T toobj, String... fieldspec) {for (String filename : fieldspec) {Object val = ReflectionUtils.invokeGetterMethod(fromobj, filename);ReflectionUtils.invokeSetterMethod(toobj, filename, val);}}public static void main(String[] args) {Pmdept dept1 = new Pmdept();dept1.setAddTime(new Date());dept1.setDeptCode("1code");dept1.setDeptDesc("1desc");dept1.setDeptName("1name");dept1.setId(1);Pmdept dept2 = new Pmdept();dept2.setId(2);Pmuser user = null;copyProperties(dept1, user = new Pmuser(), "id");System.out.println(user.getId());}/**調用Getter方法* @param obj 對象* @param propertyName 屬性名* @return */public static Object invokeGetterMethod(Object obj,String propertyName){String getterMethodName = "get"+StringUtils.capitalize(propertyName);return invokeMethod(obj, getterMethodName, null, null);}/**調用Setter方法,不指定參數的類型* @param obj* @param propertyName* @param value*/public static void invokeSetterMethod(Object obj,String propertyName,Object value){invokeSetterMethod(obj, propertyName, value, null);}/**調用Setter方法,指定參數的類型* @param obj* @param propertyName* @param value* @param propertyType 為空,則取value的Class*/public static void invokeSetterMethod(Object obj,String propertyName,Object value,Class<?> propertyType){propertyType = propertyType != null ? propertyType : value.getClass();String setterMethodName = "set"+StringUtils.capitalize(propertyName);invokeMethod(obj, setterMethodName, new Class<?>[]{propertyType}, new Object[]{value});}/**直接調用對象方法,忽視private/protected修飾符* @param obj* @param methodName* @param parameterTypes* @param params* @return */public static Object invokeMethod(final Object obj,final String methodName, final Class<?>[] parameterTypes,final Object[] args) {Method method = obtainAccessibleMethod(obj, methodName, parameterTypes);if (method == null) {throw new IllegalArgumentException("Devkit: Could not find method [" + methodName+ "] on target [" + obj + "].");}try {return method.invoke(obj, args);} catch (IllegalAccessException | IllegalArgumentException| InvocationTargetException e) {e.printStackTrace();}return null;}/**循環向上轉型,獲取對象的DeclaredMethod,并強制設置為可訪問* 如向上轉型到Object仍無法找到,返回null* * 用于方法需要被多次調用的情況,先使用本函數先取得Method,然后調用Method.invoke(Object obj,Object... args)* @param obj* @param methodName* @param parameterTypes* @return */public static Method obtainAccessibleMethod(final Object obj,final String methodName, final Class<?>... parameterTypes) {Class<?> superClass = obj.getClass();Class<Object> objClass = Object.class;for (; superClass != objClass; superClass = superClass.getSuperclass()) {Method method = null;try {method = superClass.getDeclaredMethod(methodName,parameterTypes);method.setAccessible(true);return method;} catch (NoSuchMethodException | SecurityException e) {// Method不在當前類定義,繼續向上轉型}}return null;}/*** 不能確定方法是否包含參數時,通過方法名匹配獲得方法* @param obj* @param methodName* @return */public static Method obtainMethod(final Object obj,final String methodName){Class<?> clazz = obj.getClass();Method[] methods = METHODS_CACHEMAP.get(clazz);if (methods == null) { // 尚未緩存methods = clazz.getDeclaredMethods();METHODS_CACHEMAP.put(clazz, methods);}for (Method method : methods) {if (method.getName().equals(methodName))return method;}return null;}/**直接讀取對象屬性值* 忽視private/protected修飾符,不經過getter函數* @param obj* @param fieldName* @return */public static Object obtainFieldValue(final Object obj,final String fieldName){Field field = obtainAccessibleField(obj, fieldName);if(field == null){throw new IllegalArgumentException("Devkit: could not find field ["+fieldName+"] on target ["+obj+"]");}Object retval = null;try {retval = field.get(obj);} catch (IllegalArgumentException | IllegalAccessException e) {e.printStackTrace();}return retval;}/**直接設置對象屬性值* 忽視private/protected修飾符,不經過setter函數* @param obj* @param fieldName* @param value*/public static void setFieldValue(final Object obj,final String fieldName,final Object value){Field field = obtainAccessibleField(obj, fieldName);if(field == null){throw new IllegalArgumentException("Devkit: could not find field ["+fieldName+"] on target ["+obj+"]");}try {field.set(obj, value);} catch (IllegalArgumentException | IllegalAccessException e) {e.printStackTrace();}}/**循環向上轉型,獲取對象的DeclaredField,并強制設為可訪問* 如向上轉型Object仍無法找到,返回null* @param obj* @param fieldName* @return */public static Field obtainAccessibleField(final Object obj,final String fieldName) {Class<?> superClass = obj.getClass();Class<Object> objClass = Object.class;for (; superClass != objClass; superClass = superClass.getSuperclass()) {try {Field field = superClass.getDeclaredField(fieldName);field.setAccessible(true);return field;} catch (NoSuchFieldException | SecurityException e) {e.printStackTrace();}}return null;}}
轉載于:https://my.oschina.net/foggy/blog/57440
總結
以上是生活随笔為你收集整理的反射工具类ReflectionUtils的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用js实现table增加一行
- 下一篇: 新浪微博注册用户超3亿 六成活跃者使用移