我正在尝试使用以下代码从我的对象中提取方法:
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/