package com.reflect;
import java.lang.reflect.Method;public class ReflectUitl { public static Method getMethodDemo(Class clazz, String methodName, final Class[] classes) { Method method = null; // methodName 方法名称, classes 方法类型参数数据 try { method = clazz.getDeclaredMethod(methodName, classes); } catch (NoSuchMethodException e) { try { clazz.getMethod(methodName, classes); } catch (NoSuchMethodException e1) { if (clazz.getSuperclass() == null) { return method; } else { method = getMethodDemo(clazz.getSuperclass(), methodName, classes); } } } return method; } public static Object invoke(Object obj, String methodname, Class[] classes, Object[] object) { Method method = getMethodDemo(obj.getClass(), methodname, classes); method.setAccessible(true); Object inObj = null; try { inObj = method.invoke(obj, object); } catch (Exception e) { System.out.println(e.getMessage()); } return inObj; } public static Object invoke(final Object obj, final String methodName) { return invoke(obj, methodName, new Class[] {}, new Object[] {}); } public static Object invoke(final Object obj, final String methodName, final Class[] classes) { return invoke(obj, methodName, classes, new Object[] {}); } public static void main(String[] args) throws Exception { ReflectUitl.invoke(new Demo2(), "printlnB"); }// demo2 类, 自行定义。
}