【问题标题】: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

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 2017-07-16
    • 2012-07-31
    • 2014-01-15
    • 2015-07-04
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多