任务描述
本关任务:
1.使用字节码对象获取该类中定义公用方法。遍历输出该方法名。
相关知识
1.1 获取当前类中定义的所有方法
要获取当前类中定义的所有方法可以通过 Class 中的 getDeclaredMethods 函数,它会获取到当前类中的 public、default、protected、private 的所有方法。代码示例如下 :
这里需要注意的是 getDeclaredMethod 和 getDeclaredMethods 包含 private、protected、default、public 的函数,并且通过这两个函数获取到的只是在自身中定义的函数,从父类中集成的函数不能够获取到。而 getMethod 和 getMethods 只包含 public 函数,父类中的公有函数也能够获取到。
根据提示,在右侧编辑器补充代码,完成以下任务:
1.使用字节码对象获取该类中定义公用方法。遍历输出改方法名。
2.学会使用反射获取类中指定方法
package step2; import java.lang.reflect.Method; public class ReflectFunc { public static void main(String[] args) { Class<Student> studentClass = Student.class; //---------------------Begin------------------------ //根据上方的字节码对象,获取定义的方法并遍历输出 Method[] methods = studentClass.getDeclaredMethods(); for (Method method : methods) { System.out.println("declared method name : " + method.getName()); } try { // 获取Student中名为getName的方法 Method getAge = studentClass.getMethod("getAge"); System.out.println(getAge); } catch (Exception e) { e.printStackTrace(); } //System.out.print("sayHello"); // 获取 Student 类中的getAge方法并将其打印输出 // ---------------------End------------------------ } }