黑马程序员技术交流社区

标题: Java如何使用反射调用父类的方法 [打印本页]

作者: 何小红    时间: 2012-9-21 22:08
标题: Java如何使用反射调用父类的方法
本帖最后由 何小红 于 2012-9-21 22:10 编辑

Java如何使用反射调用父类的方法
求各位帮我看看
作者: 程振    时间: 2012-9-21 23:35
  1. import java.lang.reflect.InvocationTargetException;
  2. import java.lang.reflect.Method;

  3. class Father{
  4.         public void fromFather(){
  5.                 System.out.println("Method of Father");
  6.         }
  7. }
  8. class Son extends Father{
  9. }

  10. public class ReflectionDemo {
  11.         public static void main(String[] args) throws Exception {
  12.                 Class sonClass = Son.class;
  13.                 Class fatherClass = sonClass.getSuperclass();
  14.                
  15.                 Method[] method = fatherClass.getMethods();
  16.                 for(Method tmp : method){
  17.                         if(tmp.getName() == "fromFather")
  18.                         tmp.invoke(fatherClass.newInstance(), new Object[]{});
  19.                 }
  20.         }
  21. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2