JAVA——反射工具類
通過方法名調用方法
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * 反射相關輔助方法 * @author Louis * @date Aug 19, 2018 */ public class ReflectionUtils { /** * 根據方法名調用指定對象的方法 * @param object 要調用方法的對象 * @param method 要調用的方法名 * @param args 參數對象數組 * @return */ public static Object invoke(Object object, String method, Object... args) { Object result = null; Class<? extends Object> clazz = object.getClass(); Method queryMethod = getMethod(clazz, method, args); if(queryMethod != null) { try { result = queryMethod.invoke(object, args); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } else { try { throw new NoSuchMethodException(clazz.getName() + " 類中沒有找到 " + method + " 方法。"); } catch (NoSuchMethodException e) { e.printStackTrace(); } } return result; } /** * 根據方法名和參數對象查找方法 * @param clazz * @param name * @param args 參數實例數據 * @return */ public static Method getMethod(Class<? extends Object> clazz, String name, Object[] args) { Method queryMethod = null; Method[] methods = clazz.getMethods(); for(Method method:methods) { if(method.getName().equals(name)) { Class<?>[] parameterTypes = method.getParameterTypes(); // 判斷傳遞的參數個數是否與方法參數的個數相同,可能存在重載的方法 if(parameterTypes.length == args.length) { boolean isSameMethod = true; // 判斷傳遞的參數類型是否與方法參數類型相同 for(int i=0; i<parameterTypes.length; i++) { Object arg = args[i]; if(arg == null) { arg = ""; } if(!parameterTypes[i].equals(args[i].getClass())) { isSameMethod = false; } } if(isSameMethod) { queryMethod = method; break ; } } } } return queryMethod; } }