Java反射原理分析 - Method篇

反射方法剖析

Class对象提供以下获取对象的方法(Method):

  • getMethod - 返回类或接口的特定方法,只能是public修饰的方法。
  • getDeclaredMethod - 返回类或接口的特定方法。
  • getMethods - 返回类或接口的所有public方法,包括父类的public方法。
  • getDeclaredMethods - 返回类或接口的所有方法,包括 public、protected、默认(包)访问和 private 方法,但不包括继承的方法。
测试用例
//父类
public class RefFather {
   
    public void refFatherMethod(){
   
        System.out.println("我是父类方法 refFatherMethod");
    }
}

//子类
public class RefSon extends RefFather{
   
    private void refSonMethod(){
   
        System.out.println("我是子类方法 refMethod");
    }
}

//测试方法
public static void main(String[] args) {
   
    try {
   
            //类的全限定名 即包名+类名
            Class<?> clz = Class.forName("main.ref.RefSon");
            Object obj = clz.newInstance();
            Method refFatherMethod = clz.getMethod("refFatherMethod");
            Method refSonMethod = clz.getDeclaredMethod("refSonMethod");
            refSonMethod.invoke(obj);
     } catch (Exception e) {
   
            e.printStackTrace();
     }
}

Method

先看Class.getMethod(String name, Class<?>... parameterTypes)的源码:

@CallerSensitive
public Method getMethod(String name, Class<?>... parameterTypes)
    throws NoSuchMethodException, SecurityException {
   
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
    Method method = getMethod0(name, parameterTypes, true);
    if (method == null) {
   
        throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
    }
    return method;
}

上面源码我们只需要重点解决以下疑问就可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值