【问题标题】:I want to search for a method inside a java class. I have method name as String and name of the class in which I am looking into [duplicate]我想在 java 类中搜索一个方法。我有方法名称作为字符串和我正在研究的类的名称[重复]
【发布时间】:2017-01-28 22:30:20
【问题描述】:
class A {
method x() {
}
method y() {
}
}
class B {
A a = new A();
String methodName = "x";
// I want to execute this statement **a.x();**
}
我知道方法名称,我想自动调用该方法。
【问题讨论】:
标签:
java
methods
reflection
【解决方案1】:
在您的情况下,只需致电:
a.getClass().getMethod(methodName, null).invoke(a);
记住抛出的异常:
NoSuchMethodException
InvocationTargetException
IllegalAccessException
并公开x 方法或只使用getDeclaredMethod 而不是getMethod。