按例子讲,比较易懂。
例子:一个Test类,Test类中有run方法,通过字符串“run”执行该类的对象的run方法。
java代码:
1.类
public class Test { public void run(String a){ System.out.println(a+"反射的测试方法"); }}2.实现方法
public static void main(String[] args) { String methodName="run"; Class formatter=Test.class; Test t1=new Test(); Method cMethod; try { cMethod = formatter.getMethod(methodName, new Class[]{String.class}); String aa=(String) cMethod.invoke(t1, new Object[]{"罗成"}); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } }其中,
1.Method cMethod = formatter.getMethod(方法名, 参数的类型类数组);
2.cMethod.invoke(执行方法的对象, 参数数组);
其中2的放回值是object