java反射invoke方法的使用

invoke 主要是用来调用某个类中的方法的,但是他不是通过当前类直接去调用而是通过反射的机制去调用。

在这之前我们先新建一个实体类,一会会用到。

public class TestMode {
    private static final String TAG = "TestMode";

    private int age;

    String name;


    int length;
    public TestMode() {
    }

    public TestMode(int age, String name, int length) {
        this.age = age;
        this.name = name;
        this.length = length;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }


    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    private void testReflect(String msg) {
        System.out.println(msg);
    }

    @Override
    public String toString() {
        return "TestMode{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", length=" + length +
                '}';
    }
}

 

然后我们上个测试类:

public class ReflectTest {
    public static void main(String args[]) {
        TestMode testMode = new TestMode(30, "明", 170);
        //获取class 对象
        Class cla = testMode.getClass();
        //获取去类中的所有方法,返回一个method数组
        Method[] methods = cla.getDeclaredMethods();
        for (Method method : methods) {
            method.setAccessible(true);
            //获取当前方法的修饰符参数
            int modifiers = method.getModifiers();
            //获取该方法的参数
            Class<?>[] types= method.getParameterTypes();
           //只调用私有方法,并且参数必须是一个
            if (modifiers == Modifier.PRIVATE && types.length==1) {
                try {

                    method.invoke(testMode, "我要开始调用方法了" + method.getName());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}

执行结果:

我要开始调用方法了testReflect
1. getDeclaredMethods()  是Class 类的方法,它返回了当前类的所有的方法数组 Method[]数组,
Method是方法相关参数的封装类。

2. getModifiers() 是method 类中的方法,通过该方法我们可以获取该方法的修饰符 类如 public 等,

java 中Modifier 类定义了所有的修饰符。

3. getParameterTypes() 是method 类中的方法,通过该方法能够返回当前方法的所有参数的class[] 数组,并且是顺序的。

4. invoke(Object obj, Object... args) 是method 类中的方法,这个方法是一个native 方法

  obj: 调用类的实例对象

  args:调用发方法的参数,是可变长度的

通过 method.invoke(obj , args ) 可以实现method 方法的调用,并通过args 参数传参。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章