将方法名称作为字符串给出时,如何调用Java方法? [英] How do I invoke a Java method when given the method name as a string?

查看:119
本文介绍了将方法名称作为字符串给出时,如何调用Java方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个变量:

Object obj;
String methodName = "getName";

不知道 obj 的类,如何我可以调用 methodName 标识的方法吗?

Without knowing the class of obj, how can I call the method identified by methodName on it?

被调用的方法没有参数,并且字符串返回值。它是一个Java bean的getter

The method being called has no parameters, and a String return value. It's a getter for a Java bean.

推荐答案

从臀部编码,它会像:

java.lang.reflect.Method method;
try {
  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) { ... }
  catch (NoSuchMethodException e) { ... }

参数标识您需要的非常具体的方法(如果有多个可用的重载,如果方法没有参数,则只给 methodName )。

The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give methodName).

然后通过调用

try {
  method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) { ... }
  catch (IllegalAccessException e) { ... }
  catch (InvocationTargetException e) { ... }

如果不这样做,请忽略 .invoke 中的参数有什么。但是,是的。阅读 Java反思

Again, leave out the arguments in .invoke, if you don't have any. But yeah. Read about Java Reflection

这篇关于将方法名称作为字符串给出时,如何调用Java方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆