Method 中的 invoke()

来源:互联网 发布:淘宝客刷销量 编辑:程序博客网 时间:2024/05/15 07:10

import java.lang.reflect.Method;   

  

public class InvokeTest{   

  

 public int add(int x, int y) {   

  return x+ y;   

 }   

  

 public String print(String message) {   

  return "hello" + message;   

 }   

  

 public static void main(String[] args) throws Exception {   

     

  Method addMethod = InvokeTest.class.getMethod("add"new Class[] { int.class,   

    int.class });   

  //Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,   

  //如果参数为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象,   

  //如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象,   

  //再将其返回   

  Object result = addMethod.invoke(InvokeTest.class.newInstance()new Object[] {   

    new Integer(200), new Integer(200) });   

 

  System.out.println(result);   

  

  Method echoMethod = InvokeTest.class.getMethod("echo",   

    new Class[] { String.class });   

  String message = echoMethod.invoke(InvokeTest.class.newInstance()new Object[] { "你好" });   

  System.out.println(message);   

 }   

原创粉丝点击