通过反射访问方法(学习笔记)

这一节的讲解我们也分为三个小部分,和上一节讲的访问成员变量的形式差不多,分别是

  1. 通过getMethods()等方法获得类中的方法,然后以数组形式返回

  2. 通过getName(),isVarAges()等方法获得该方法的具体信息

  3. 通过invoke(Object obj,Object…Args)利用指定参数Args执行制定对象obj中的该方法,返回值为Object类型

    首先我们先来看第一部分,通过getMethods()等方法获得类中的方法

 getMethods()  此方法获得所有权限为public的方法,按指定顺序以数组形式返回
 getMethod(String name) 获得权限为public的指定方法
 getDelcareMethods() 获得所有方法,按指定顺序以数组形式返回
 getDelcareMethod(String name) 获得指定方法

接下来的二三部分我们还是看代码

public class Example_03 {
    static void staticM(){
        System.out.println("执行staticM方法");
    }
    public int intM(int i){
        System.out.println("执行public intM方法");
        return i;
    }
    protected int protectedM(String s,int i)
        throws NumberFormatException{
        System.out.println("执行protectedM方法");
        return Integer.valueOf(s)+i;
    }
    private String privateM(String...strings){
        System.out.println("执行privateM方法");
        StringBuffer stringBuffer=new StringBuffer();
        for (int i = 0; i < strings.length; i++) {
            stringBuffer.append(strings[i]);
        }
        return stringBuffer.toString();
    }

}

上述代码我们创建了几个方法,其中他们的返回类型,传入参数的类型,权限修饰符各不相同

package annotation;

import java.lang.reflect.Method;

public class Main_03 {
    public static void main(String[] args) {
        Example_03 example=new Example_03();//创建一个Example_03的对象,example
        Class exampleC=example.getClass();//利用getClass()方法返回一个Class对象
        Method[] declareMethod=exampleC.getDeclaredMethods();
        //通过Class获得example中所有的方法,以数组形式返回
        for (int i = 0; i < declareMethod.length; i++) {//遍历example对象中的方法
            Method method=declareMethod[i];
            System.out.println("名称为:"+method.getName());//通过getName()获得方法名称
            System.out.println("是否含有可变数量的参数:"+method.isVarArgs());
            //通过isVarArgs()查看是否带有可变数量的参数,如果有,返回true
            Class [] paraTypes=method.getParameterTypes();
            //通过getParameterTypes()获得此方法所有传入参数的类型,返回一个Class类对象数组
            System.out.println("入口参数类型依次为:");
            for (int j = 0; j < paraTypes.length; j++) {
                System.out.println(""+paraTypes[j]);//输出入口参数类型
            }
            System.out.println("异常依次为:");
            Class[] expection=method.getExceptionTypes();
            //通过getExceptionTypes()获得此方法所有可能发生的异常,返回一个Class类对象数组
            for (int j = 0; j < expection.length; j++) {
                System.out.println(""+expection[j]);//输出异常
            }
            boolean isturn=true;
            while(isturn){

                try {
                    isturn=false;
                    if ("staticM".equals(method.getName())) {//判断方法的名称
                        method.invoke(example);//执行方法

                    }else if("intM".equals(method.getName())){//判断方法的名称
                        System.out.println("返回值为:"+method.invoke(example, 168));//使用指定参数执行方法
                    }else if("protectedM".equals(method.getName())){//判断方法的名称
                        System.out.println("返回值为:"+method.invoke(example, "7",5));//使用指定参数执行方法
                    }else if ("privateM".equals(method.getName())) {//判断方法的名称
                        Object[] strings=new Object[]{new String[]{"M","Y","X"}};//使用指定参数执行方法
                        System.out.println("返回值为:"+method.invoke(example, strings));
                    }

                } catch (Exception e) {
                    // TODO: handle exception
                    System.out.println("输出异常解决方法");
                    method.setAccessible(true);//定义允许访问私有方法
                    isturn=true;
                }
            }
            System.out.println();
        }

    }

}

输出结果为

名称为:staticM
是否含有可变数量的参数:false
入口参数类型依次为:
异常依次为:
执行staticM方法

名称为:intM
是否含有可变数量的参数:false
入口参数类型依次为:
int
异常依次为:
执行public intM方法
返回值为:168

名称为:protectedM
是否含有可变数量的参数:false
入口参数类型依次为:
class java.lang.String
int
异常依次为:
class java.lang.NumberFormatException
执行protectedM方法
返回值为:12

名称为:privateM
是否含有可变数量的参数:true
入口参数类型依次为:
class [Ljava.lang.String;
异常依次为:
输出异常解决方法
执行privateM方法
返回值为:MYX

上述代码中为我们演示了获取方法的具体信息,和使用invoke(Object obj,Object…Args)执行制定方法,并且返回值

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值