如何获得像“method1.method2”ClassLoader这样的方法?

时间:2013-07-27 22:11:56

标签: java classloader getmethod

我是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();

1 个答案:

答案 0 :(得分: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