java - 在java反射中找不到方法

标签 java reflection

我正在尝试使用以下代码从我的对象中提取方法:

Method[] methods = instance.getClass().getMethods();

for (Method m : methods) {
    System.out.println(">>> " + m.getName());
    for (Class c : m.getParameterTypes()) {
        System.out.println("\t->>> " + c.getName());
    }
}

Object method = instance.getClass().getMethod("initialize", ComponentContext.class);

它打印以下输出:

>>> initialize
->>> org.hive.lib.component.ComponentContext
java.lang.NoSuchMethodException: org.hive.sample.Calculator.initialize(org.hive.lib.component.ComponentContext)
at java.lang.Class.getMethod(Class.java:1624)
at org.hive.container.lib.Component.hasRightParent(Component.java:140)
at org.hive.container.lib.Component.<init>(Component.java:118)
at org.hive.container.lib.ComponentController$AppLoader.execute(ComponentController.java:107)
at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)

原始源代码:

class Calculator {
    @Override
    public void initialize(ComponentContext context) {
        //  Do nothing
    }
}

怎么了?

添加:我已将获取方法更改为:

Object method = instance.getClass().getMethod("initialize", org.hive.lib.component.ComponentContext.class);

但还是出现异常

添加 2: instance 对象是使用 JCL 从 JAR 实例化的,这可能是问题所在吗?

最佳答案

传递给 getMethod()ComponentContext 类可能与您的代码转储的类不相同(在 JVM 看来)- 如果是由不同的类加载器加载。检查关联的类加载器是否相等只是为了确定。

这类似于 Java, getting class cast exception where both classes are exactly the same

关于java - 在java反射中找不到方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19347264/

相关文章:

java - SQL 到 JPQL - 半正矢公式

java - Java 中的 3D 转换

c# - 如何动态评估 C# 表达式?

c# - 如何从一个类中读取另一个类中的文档?

java - JDBC & 死锁避免题(基础)

java - 为什么我的 while 进入无限循环?我如何解决它?

java - 我如何更改此方法以使用 ArrayList?

asp.net - System.Reflection.Assembly.LoadFile 锁定文件

c# - 为什么方法调用会因参数异常而失败?

去反射 : get correct struct type of interface