Method invoke 使用说明


import lombok.Data;

import java.util.Arrays;

/**
 * @author admin
 */
@Data
public class MyPeople {

    private int age;
    private String name;

    public void eat1(String ... footNames){
        System.out.print("name[" + this.name + "],age[" + this.age + "],");
        System.out.print("eat footName is");
        if(footNames != null){
            Arrays.asList(footNames).forEach(footName -> System.out.print(footName + ","));
        }
    }

    public void eat2(int footNum,String ... footNames){
        System.out.print("name[" + this.name + "],age[" + this.age + "],");
        System.out.print("eat " + footNum + " foot,footName is");
        System.out.print("eat footName ");
        if(footNames != null){
            Arrays.asList(footNames).forEach(footName -> System.out.print(footName + ","));
        }
    }

}
参数说明
name指的是方法名称
java.lang.Class<T> @Contract(pure = true) 
@NotNull 
public reflect.Method getMethod(@NonNls @NotNull String name,
                                Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException



obj指的是类的实例,可以为null
java.lang.reflect.Method public Object invoke(Object obj,
                     Object... args)
throws IllegalAccessException, IllegalArgumentException, reflect.InvocationTargetException

import java.lang.reflect.Method;

public class ReflectTest {

    public static void main(String[] args) {
        MyPeople myPeople = new MyPeople();
        myPeople.setAge(12);
        myPeople.setName("gaoshan");
        Class<MyPeople> myPeopleClass = MyPeople.class;
        try {
            Method eatMethod1 = myPeopleClass.getMethod("eat1",String[].class);
            eatMethod1.invoke(myPeople,new Object[]{new String[]{"aa","bb","cc"}});
            System.out.println();
            Method eatMethod2 = myPeopleClass.getMethod("eat2",int.class,String[].class);
            eatMethod2.invoke(myPeople,100,new String[]{"aa","bb","cc"});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行结果

name[gaoshan],age[12],eat footName isaa,bb,cc,
name[gaoshan],age[12],eat 100 foot,footName iseat footName aa,bb,cc,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值