Java反射机制-调用方法

来源:互联网 发布:端口攻击器 编辑:程序博客网 时间:2024/05/15 04:03

通常调用方法都是通过类名.方法名  或是  对象名.方法名  进行方法调用。

在反射中,调用方法需要使用Method类

Method类的一个对象可以看作是一个方法,可以通过操作Method类的对象来操作方法。

Method类的对象可以通过Class类对象中的getMethod()方法和getDeclaredMethod()方法来获取。

需要注意的是getMethod()方法只能获取当前类的公有方法,而getDeclaredMethod方法可以获取当前类的所有方法。

Method类有几个常用的方法如下:

   invoke() Method对象通过此方法来调用我们传过去的方法,方法中的对象需要包含Method对象对应的方法

    setAccessible() 这是Java的检查机制,true是不检查,false是检查。默认的是false,调用私有方法时需要用到

    getName()此方法的名称

    getDeclaringClass 这个方法属于哪个类

             getReturnType 此方法的返回值类型

    getParameters() 此方法的参数列表 

      getParameterCount() 此方法的参数数量
package test3;public class ClassA {private void show2() {int num = 0;for (int i = 1; i < 10000; i++) {num += i;}System.out.println(num);}public int show() {int num = 0;for (int i = 1; i < 10000; i++) {num += i;}System.out.println(num);return num;}}

package test3;import java.lang.reflect.Method;public class infoClass {    public void callMethod(Class<?> c,String methodName) throws  Exception{    Method method=c.getDeclaredMethod(methodName);method.setAccessible(true);//关闭Java的检查机制method.invoke(c.newInstance());//调用此方法}}

package test3;public class TestMain {public static void main(String[] args) throws Exception {infoClass i=new infoClass();i.callMethod(ClassA.class,"show2");
                i.callMethod(ClassA.class,"show");
}}

上面分别调用了ClassA中的私有方法show2和公有方法show
  
  注意: 关闭检查调用方法的速度要比开启检查调用方法的速度要快。

原创粉丝点击