通过反射,可以获取方法等相关内容。
示例如下:
1、实体类Emp2
public class Emp2 {
public void m1(){
System.out.println("this is a method with no parameter!");
}
public void m2(String s){
System.out.println("this is a method with a String parameter, the value of the paramter is :" + s);
}
public static void m3(){
System.out.println("this is a static method with not parameter!");
}
}
2、调用
(1)调用m1
Method m1 = Emp2.class.getMethod("m1",null);
m1.invoke(new Emp2(), null);
结果如下:
this is a method with no parameter!
(2)调用m2
Method m2 = Emp2.class.getMethod("m2", String.class);
m2.invoke(new Emp2(), " yy");
结果如下:
this is a method with a String parameter, the value of the paramter is : yy
(3)调用m3
Method m3 = Emp2.class.getMethod("m3", null);
m3.invoke(null, null);
结果如下:
this is a static method with not parameter!
(4)获取m3返回值类型
System.out.println(m3.getReturnType());
结果如下:
void
可以看出:
对于static的方法,第一次参数可以传入null。
对于参数类型,若方法有参数,比如传入对应的类型。若没有,传入null。