【问题标题】:How can get methods like "method1.method2" ClassLoader?如何获得像“method1.method2”ClassLoader 这样的方法?
【发布时间】:2013-07-27 22:11:56
【问题描述】:

我是 Java 中 ClassLoader 问题的新手。那么我怎样才能调用像

这样的方法
getDefault().GetImage();

这是我当前的代码:

ClassLoader tCLSLoader = new URLClassLoader(tListURL);
Class<?> tCLS = tCLSLoader.loadClass("com.github.sarxos.webcam.Webcam");

// MY FAILED TEST
Method tMethod = tCLS.getDeclaredMethod("getDefault().GetImage"); 
tMethod.invoke(tCLS,  (Object[]) null);

编辑:

我试过这个:

Method tMethod1 = tCLS.getDeclaredMethod("getDefault");
Object tWebCam = tMethod1.invoke(tCLS,  (Object[]) null);

// WebCam - Class
Class<?> tWCClass = tWebCam.getClass();


Method tMethod2 = tWCClass.getDeclaredMethod("getImage");
tMethod2.invoke(tWCClass, (Object[]) null);

但我明白了:

java.lang.IllegalArgumentException: object is not an instance of declaring class

我需要得到这个结果:

BufferedImage tBuffImage = Webcam.getDefault().getImage();

【问题讨论】:

  • 呃,有趣。不完全是 Java 的工作原理。你到底想做什么?你当然不能这样做。你需要知道getDefault()的返回类型是什么,强制转换然后调用next方法。
  • 再看帖子,我修改了。谢谢!
  • 你需要传入实例而不是Class所以tMethod2.invoke(tWebCam, (Object[]) null);
  • 我明白了!!!!非常感谢!!! :)

标签: java classloader getmethod


【解决方案1】:

你不能这样做,这不是反射的工作原理。

您需要将String 拆分为.,然后依次循环和调用方法。

这应该可以工作

private static Object invokeMethods(final String methodString, final Object root) throws Exception {
    final String[] methods = methodString.split("\\.");
    Object result = root;
    for (final String method : methods) {
        result = result.getClass().getMethod(method).invoke(result);
    }
    return result;
}

快速测试:

public static void main(String[] args) throws Exception {
    final Calendar cal = Calendar.getInstance();
    System.out.println(cal.getTimeZone().getDisplayName());
    System.out.println(invokeMethods("getTimeZone.getDisplayName", cal));
}

输出:

Greenwich Mean Time
Greenwich Mean Time

【讨论】:

  • 类不能是静态的,方法可以是静态的。在这种情况下,这应该仍然有效,从 JavaDoc 如果底层方法是静态的,那么指定的 obj 参数将被忽略。它可能为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
相关资源
最近更新 更多