这篇讲讲如何利用反射机制调用方法,需要用到Method类(java.lang.reflect),获取Method对象一般有如下四种方法。
1.Method getMethod(String name, Class<?>... parameterTypes)
返回某对象指定的类的指定的共有方法,name参数表示方法名称,parameterTypes表示方法的参数类型的Class对象,且该参数数量可变,若方法为无参方法,就用null代替。
2.Method getDeclaredMethod(String name, Class<?>... parameterTypes)
返回某对象指定的类的指定的方法(与方法的权限修饰符无关),name参数表示方法名称,parameterTypes表示方法的参数类型的Class对象,且该参数数量可变,若方法为无参方法,就用null代替。
3.Method [] getMethods()
返回某Class对象对应的类的全部共有方法
4.Method [] getDeclaredMethods()
返回某Class对象指定的类的全部方法,与方法的权限修饰符无关
Employee emp = new Employee("李建国", 90, 100);
Class cla = Employee.class;
try {
Method met1 = cla.getMethod("toString", null);
System.out.println(met1.invoke(emp, null));
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
控制台上输出:Employee{name='李建国', age=90, salary=100.0, status=null}