【问题标题】:Is there any way to search for, and then call a method in java from a String?有没有办法搜索,然后从字符串调用java中的方法?
【发布时间】:2014-05-05 17:17:08
【问题描述】:

我问是否有一种方法可以获得字符串(即 "Foo.bar();" ),并在我的 jvm 中搜索类 Foo 并调用静态方法 bar?如果有,可以分享一下吗?

【问题讨论】:

  • 是的,有办法。 (我假设这没有多大帮助。不要反问问题。你的真正意思是:'你怎么......?')
  • XY problem,也许?
  • Here 是关于反射的教程。但似乎您还需要一个解析器。这是关于表达语言的一个完全不同的主题。

标签: java string methods call


【解决方案1】:

这里是使用 Java 反射:

try {
    Class<?> myClass = Class.forName("Foo");
    Method myMethod = myClass.getMethod("bar");
    Object retObject = myMethod.invoke(null);
} catch (Exception e) {
    // handle errors here...
    e.printStackTrace();
}

这是如果bar()在这里是一个静态方法,如果它没有参数。

有关反射的更多信息,请参阅this tutorial

【讨论】:

  • @Leo:这里也一样......对我来说,这实际上似乎回答了这个问题。
猜你喜欢
  • 1970-01-01
  • 2018-04-17
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
  • 2021-03-19
相关资源
最近更新 更多