Java反射中Method类invoke方法的用法

/**
 * InvokeTester.java
 * 版权所有(C) 2010 cuiran2001@163.com
 * 创建:崔冉  2010-2-9 下午02:07:13
 */
package com.timer.demo.objectsocket;

import java.lang.reflect.Method;

/**
 * @author 崔冉
 *
 */
public class InvokeTester {
	public int add(int param1, int param2) {
		  return param1 + param2;
    }

	public String echo(String mesg) { 

		  return "echo" + mesg;
	}
	public static void main(String[] args) throws Exception {
		  Class classType = InvokeTester.class;
		  Object invokertester = classType.newInstance();
		  
		  Method addMethod = classType.getMethod("add", new Class[] { int.class,
		    int.class });
		  //Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,
		  //如果参数为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象,
		  //如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象,
		  //再将其返回
		  
		  Object result = addMethod.invoke(invokertester, new Object[] {
		    new Integer(100), new Integer(200) });
		  //在jdk5.0中有了装箱 拆箱机制 new Integer(100)可以用100来代替,系统会自动在int 和integer之间转换
		  System.out.println(result);

		  Method echoMethod = classType.getMethod("echo",
		    new Class[] { String.class });
		  result = echoMethod.invoke(invokertester, new Object[] { "hello"});
		  System.out.println(result);
		 }



}


  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cuiran

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值