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需要调用对应类实例的方法,类的非静态方法属于对象,不属于类本身。