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 参数传参。

 

 

 

  • 23
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值