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

public Object invoke(Object obj,
                     Object... args)
              throws IllegalAccessException,
                     IllegalArgumentException,
                     InvocationTargetException

对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。个别参数被自动解包,以便与基本形参相匹配,基本参数和引用参数都随需服从方法调用转换。

 

如果底层方法是静态的,那么可以忽略指定的 obj 参数。该参数可以为 null。

如果底层方法所需的形参数为 0,则所提供的 args 数组长度可以为 0 或 null。 

如果底层方法是静态的,并且尚未初始化声明此方法的类,则会将其初始化。

如果方法正常完成,则将该方法返回的值返回给调用者;如果该值为基本类型,则首先适当地将其包装在对象中。但是,如果该值的类型为一组基本类型,则数组元素 被包装在对象中;换句话说,将返回基本类型的数组。如果底层方法返回类型为 void,则该调用返回 null。

obj - 从中调用底层方法的对象(简单的说就是调用谁的方法用谁的对象)args - 用于方法调用的参数 

 

 
  1. package test922;

  2.  
  3. public class InvokeObj {

  4.  
  5. public void show() {

  6. System.out.println("无参show()方法。");

  7. }

  8. public void show (String name) {

  9. System.out.println("show方法:" + name);

  10. }

  11. public String[] arrayShow (String[] arr) {

  12. return arr;

  13. }

  14. public String StringShow (String str) {

  15. return str;

  16. }

  17. public int intShow (int num) {

  18. return num;

  19. }

  20. }

 
  1. package test922;

  2.  
  3. import java.lang.reflect.InvocationTargetException;

  4. import java.lang.reflect.Method;

  5.  
  6. public class MethodInvokeTest {

  7. public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

  8. Class<InvokeObj> clazz = InvokeObj.class;

  9. Method[] methods = clazz.getMethods();

  10. System.out.println("以下输出InvokeObj类的方法:");

  11. for (Method method : methods) {

  12. System.out.println(method);

  13. }

  14. System.out.println("InvokeObj类的无参show()方法:");

  15. Method method1 = clazz.getMethod("show", null);

  16. //会执行无参show()方法

  17. Object obj = method1.invoke(new InvokeObj(),null);

  18. System.out.println("输出无参show()方法的返回值:"+obj);

  19. System.out.println("InvokeObj类的show()方法: ");

  20. Method method2 = clazz.getMethod("show", String.class);

  21. Object obj1 = method2.invoke(new InvokeObj(), "hello,world");

  22. System.out.println("输出有参show()方法: ");

  23. System.out.println("InvokeObj类的arrayShow()方法: ");

  24. Method method3 = clazz.getMethod("arrayShow", String[].class);

  25. String[] strs = new String[]{"hello", "world", "!"};

  26. //数组类型的参数必须包含在new Object[]{}中,否则会报IllegalArgumentException

  27. String[] strings = (String[]) method3.invoke(new InvokeObj(), new Object[]{strs});

  28. for (String str : strings) {

  29. System.out.println("arrayShow的数组元素:" + str);

  30. }

  31. System.out.println("InvokeObj类的StringShow()方法: ");

  32. Method method4 = clazz.getMethod("StringShow", String.class);

  33. String string = (String) method4.invoke(new InvokeObj(), "Thinking in java");

  34. System.out.println("StringShow()方法的返回值: " + string);

  35. System.out.println("InvokeObj类的intShow()方法: ");

  36. Method method5 = clazz.getMethod("intShow", int.class);

  37. int num = (int) method5.invoke(new InvokeObj(), 89);

  38. System.out.println("intShow()方法的返回值: " + num);

  39. }

  40. }

 

 
  1. 以下输出InvokeObj类的方法:

  2. public void test922.InvokeObj.show(java.lang.String)

  3. public void test922.InvokeObj.show()

  4. public java.lang.String[] test922.InvokeObj.arrayShow(java.lang.String[])

  5. public java.lang.String test922.InvokeObj.StringShow(java.lang.String)

  6. public int test922.InvokeObj.intShow(int)

  7. public final void java.lang.Object.wait() throws java.lang.InterruptedException

  8. public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException

  9. public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException

  10. public boolean java.lang.Object.equals(java.lang.Object)

  11. public java.lang.String java.lang.Object.toString()

  12. public native int java.lang.Object.hashCode()

  13. public final native java.lang.Class java.lang.Object.getClass()

  14. public final native void java.lang.Object.notify()

  15. public final native void java.lang.Object.notifyAll()

  16. InvokeObj类的无参show()方法:

  17. 无参show()方法。

  18. 输出无参show()方法的返回值:null

  19. InvokeObj类的show()方法:

  20. show方法:hello,world

  21. 输出有参show()方法:

  22. InvokeObj类的arrayShow()方法:

  23. arrayShow的数组元素:hello

  24. arrayShow的数组元素:world

  25. arrayShow的数组元素:!

  26. InvokeObj类的StringShow()方法:

  27. StringShow()方法的返回值: Thinking in java

  28. InvokeObj类的intShow()方法:

  29. intShow()方法的返回值: 89

 

 

 

Method getMethod(String name, Class<?>... parameterTypes)  
--返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。  

方法后面接收的就是Class类的对象,而如:String.class、int.class这些字节码才是Class类的对象

 

 

也可以此种方式:

//getMethod第一个参数是方法名,第二个参数是该方法的参数类型,
//因为存在同方法名不同参数这种情况,所以只有同时指定方法名和参数类型才能唯一确定一个方法

Method method = XXX.getClass().getMethod(methodName,new Class[0]);

 //第一个参数是具体调用该方法的对象
 //第二个参数是执行该方法的具体参数    

 

如一个函数 int Test(int a, String str);

对应的getMethod方法:

1.  getMethod("Test",int.class,String.class);

2. getMethod("Test",new Class[]{int.class,String.class});

 

 

然后通过invoke来调用此方法:

函数原型:Object Java.lang.reflect.Method.invoke(Object receiver, Object... args)

//Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,
 //如果参数为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象,
  //如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象,再将其返回

receiver:该方法所在类的一个对象

args: 传入的参数 如 100,“hello”

详细参见:http://www.linuxidc.com/Linux/2009-09/21571.htm

 

 

 

import java.lang.reflect.Method;

 

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);
 }
}

 

 

 

 

 

public class Test {
public static void main(String[] args) throws Exception {
String field = "UserName";
String methodName = "";
World world = new World();
Class xom = world.getClass();
methodName = "set"+field;
Method method = xom.getMethod(methodName, String.class);
Object[] obj = new Object[1];
obj[0] = "guolei";
method.invoke(world, obj);
// System.out.println(world.getUserName());
methodName = "get"+field;
Method method2 = xom.getMethod(methodName);
System.out.println(method2.invoke(world));

}
}

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值