一个例子弄懂invoke方法

来源:互联网 发布:奢侈品男装外套知乎 编辑:程序博客网 时间:2024/05/23 01:15
 复制代码
  1. import java.lang.reflect.Method;   
  2.   
  3. public class InvokeTester {   
  4.   
  5.  public int add(int param1, int param2) {   
  6.   return param1 + param2;   
  7.  }   
  8.   
  9.  public String echo(String mesg) {   
  10.   return "echo " + mesg;   
  11.  }   
  12.   
  13.  public static void main(String[] args) throws Exception {   
  14.   Class classType = InvokeTester.class;   
  15.   Object invokertester = classType.newInstance();   
  16.      
  17.   Method addMethod = classType.getMethod("add"new Class[] { int.class,   
  18.     int.class });   
  19.   //Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,   
  20.   //如果参数为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象,   
  21.   //如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象,   
  22.   //再将其返回   
  23.   Object result = addMethod.invoke(invokertester, new Object[] {   
  24.     new Integer(100), new Integer(200) });   
  25.   //在jdk5.0中有了装箱 拆箱机制 new Integer(100)可以用100来代替,系统会自动在int 和integer之间转换   
  26.   System.out.println(result);   
  27.   
  28.   Method echoMethod = classType.getMethod("echo",   
  29.     new Class[] { String.class });   
  30.   result = echoMethod.invoke(invokertester, new Object[] { "hello" });   
  31.   System.out.println(result);   
  32.  }   
  33. }  

转自:http://wukunlsy.javaeye.com/blog/726747

原创粉丝点击