A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 何小红 中级黑马   /  2012-9-21 22:08  /  1285 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 何小红 于 2012-9-21 22:10 编辑

Java如何使用反射调用父类的方法
求各位帮我看看

1 个回复

倒序浏览
  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. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马