当给定方法名称作为字符串时,如何调用 Java 方法? [英] How do I invoke a Java method when given the method name as a string?
问题描述
如果我有两个变量:
Object obj;
String methodName = "getName";
不知道obj
的类,如何调用上面methodName
标识的方法?
Without knowing the class of obj
, how can I call the method identified by methodName
on it?
被调用的方法没有参数,有一个 String
返回值.它是Java bean 的吸气剂.
The method being called has no parameters, and a String
return value. It's a getter for a Java bean.
推荐答案
从臀部开始编码,它会是这样的:
Coding from the hip, it would be something like:
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
).
然后您通过调用来调用该方法
Then you invoke that method by calling
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屋!