代码之家  ›  专栏  ›  技术社区  ›  skayred

在java反射中找不到方法

  •  4
  • skayred  · 技术社区  · 12 年前

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

    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中实例化的,这可能是问题所在吗?

    1 回复  |  直到 12 年前
        1
  •  3
  •   Community Mohan Dere    8 年前

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

    这与 Java, getting class cast exception where both classes are exactly the same