android反射之Method调用

public class ThirdActivity extends AppCompatActivity {
...
static public class MyTest{

        public MyTest(){}

        public void test(){
            //注意这里不能使用logi,这是android的库,main调试的时候使用的是java的库
            System.out.println("Call NoParam test");
        }

        public void test(String val){
            //注意这里不能使用logi,这是android的库,main调试的时候使用的是java的库
            System.out.println("Call Param test,param:"+val);
        }
    }


 public static void main(String[] args) throws Exception {
        Class myTestClass = MyTest.class;
        //获取无参test方法
        Method mtest_noparam = myTestClass.getDeclaredMethod("test");
       //获取有参数test方法
        Class[] program =new Class[]{String.class};
        Method mtest = myTestClass.getDeclaredMethod("test",program);
        //生成MyTest实例,注意MyTest必须是static的,因为main是static,static不能直接访问非static内部类
        Object mytestObj = myTestClass.newInstance();
        if(mtest_noparam != null){
            try {
                mtest_noparam.invoke(mytestObj);
                mtest.invoke(mytestObj,"hellow word");
            }
            catch (Exception e){
                e.printStackTrace();
            }

        }
    }
}


在这里插入图片描述
调用Methon首先获取Method。

  • 通过Class获取Method方法

    • getDeclaredMethods:获取所有声明的方法(不包含父类方法)
    • getDeclaredMethod:通过函数名称+参数列表获取声明的方法(不包含父类方法)。具体demo见上述代码
    • getMethods:获取该类的所有方法(包括父类方法)
    • getMethods:通过函数名称+参数列表获取类的方法(包括父类方法)
  • Method 判断是否是注解类方法

    • getDeclaredAnnotations:获取所有注解类的方法(不包含父类方法)
    • getAnnotation:通过注解类名获取注解类的方法(不包含父类方法)
    • getAnnotations:获取所有注解类的方法(包括父类方法)
    • getAnnotation:通过注解类名获取注解类的方法(包括父类方法)
  • Method 调用本身方法

    • invoke:必须指定一个实例,因为Method需要调用对应类实例的方法,类的非静态方法属于对象,不属于类本身。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值