【问题标题】:Java getMethod() not finding methodJava getMethod() 找不到方法
【发布时间】:2014-12-07 18:07:32
【问题描述】:

我正在尝试使用 Java 的反射为项目创建模块加载器,但 getMethod() 方法似乎拒绝定位存在的方法,即使该方法已明确定义。

在 Module.class 文件中: public final void load(org.clustermc.core.ClusterCore plugin);

我要求核心打印出它在类中找到的方法。结果:
Methods: [public void me.capit.clustersample.SampleModule.onLoad(), public void me.capit.clusterSample.SampleModule.onUnload(), public final void org.clustermc.core.Module.load(org.clustermc.core.ClusterCore), /*Other stuff from Object*/];
请注意,SampleModule 扩展了 Module。

在核心: Method enable = c.getMethod("onLoad"); Method init = c.getMethod("load", org.clustermc.core.ClusterCore.class);

onLoad() 的“启用”变量可以正常工作,但是在尝试查找 load(ClusterCore.class) 时,我得到了 NoSuchMethodException。为什么...?

【问题讨论】:

  • 如果您使用多个ClassLoaders,请确保您不会通过不同的加载器多次加载类。否则您可能会遇到ClusterCore.class 引用的运行时类与ClusterCore 参数类型不同的问题。

标签: java reflection methods


【解决方案1】:

检查 load 方法的作用域,如果是私有的则不会被访问。您需要设置可访问为真。注意 getDeclaredMethod 而不是 getMethod。

Method init = c.getDeclaredMethod("load", org.clustermc.core.ClusterCore.class);

在调用之前你需要执行这一行:-

 init.setAccessible(true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    相关资源
    最近更新 更多