java反射Method中的如何调用任意方法,即invoke()的使用

今天碰到了一个关于java反射中的Method中invoke(Object,Object...args);的使用问题,这就涉及到了反射中如何去利用这个方法去调用一个类中任意方法的问题,包括类中的静态和非静态方法,有参方法和无参的方法,经过分析总结了一些心得分享出来。

public class TestMethod {

    public static void show(int a,int b,int c){
	System.out.println("这个静态方法有参数,功能是输出a,b,c的值");
	System.out.println(a);
	System.out.println(b);
	System.out.println(c);
	System.out.println();
    }
    public static void show(){
	System.out.println("这个静态方法没有参数。。。。");
	System.out.println();
    }
    public void show(String str){
	System.out.println("这是一个 非静态 方法。功能是输出str的值。");
	System.out.println("str = "+str);
	System.out.println();
    }
    public static void fun(Method method0,Method method1,TestMethod tm ,Method method2){
	try {
	    method1.invoke(null, null);//对于静态方法第一个参数需要写null,第二个参数其实是一个Class<T>的数组,如果是无参的方法就写null
	    method0.invoke(null,1,2,3);//第一个参数同上,第二个参数中,函数原型有几个参数,就对应传入几个对应类型的参数
	    method2.invoke(tm, "一个参数,字符串而已");//因为method2不是一个静态方法,这时候第一个参数传入调用该方法的对象,第二个参数传入一个字符串
	    
	} catch (IllegalAccessException e) {
	    e.printStackTrace();
	} catch (IllegalArgumentException e) {
	    e.printStackTrace();
	} catch (InvocationTargetException e) {
	    e.printStackTrace();
	}
    }
    public static void main(String[] args) throws Exception {
	Method show0 = TestMethod.class.getMethod("show",int.class,int.class,int.class);//这个方法有参数的话就写上的参数类型的class.
	
	Method show1 = TestMethod.class.getMethod("show",null);//倘若 没有参数,就写null
	
	Method show2 = TestMethod.class.getMethod("show", String.class);//获取这个show方法,方法的参数类型是String类型的
	
	TestMethod tm  = new TestMethod();
	fun(show0,show1,tm,show2);
    }
}
瑾提供给需要的帮助的人参考学习,大神请忽略。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值