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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

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

Java如何使用反射调用父类的方法?

5 个回复

倒序浏览
子类继承和重写父类的方法,调用父类哪个方法?重写前的吗?重写前的方法,子类不具有,无法调用。若调用其他从父类继承的方法,直接使用getMethod方法得到method对象,再使用invoke方法调用就行了。
回复 使用道具 举报
public static Method getDeclaredMethod(Object object, String methodName, Class<?> ... parameterTypes){
         Method method = null ;
         for(Class<?> clazz = object.getClass() ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
             try {   
                 method = clazz.getDeclaredMethod(methodName, parameterTypes) ;   
                 return method ;  
             } catch (Exception e) {
             }
         }
         return null;
    }


调用就不说了,需要判断一下,
if( return null){
    //没有这个方法
}
回复 使用道具 举报
  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. }
复制代码
回复 使用道具 举报
使用Class的getDeclaredMethod方法,它可以获取父类的方法或者非public方法,然后调用Method的invoke方法就OK了
回复 使用道具 举报
使用Class的getDeclaredMethod方法,它可以获取父类的方法或者非public方法,然后调用Method的invoke方法就OK了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马