java - 如何获取像 "method1.method2"ClassLoader这样的方法?

标签 java classloader getmethod

我是 Java 中的类加载器问题的新手。那么我如何调用像

这样的方法
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();

最佳答案

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

您需要将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

关于java - 如何获取像 "method1.method2"ClassLoader这样的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17902961/

相关文章:

java - 仅更改方法结果和类加载器 NoSuchMethod

java - 如何将查询参数添加到 GetMethod(使用 Java commons-httpclient)?

java - 对一个类使用 Get 方法但不对另一个类使用 Get 方法时出现 NullPointEException

Java将XML转换为JSON并判断是数组还是对象

java - 在 Java 8 中测试 Lambda

java - BlackBerry 数学实用程序(Pow & Round)

scala - 如果应用程序运行很长时间,则缺少类

java - OnEnable() 中的 NullPointerException(Bukkit 插件)

maven - 从 JDK 设置 javax.xml.ws.Service,而不是使用 maven 的 javaee-api

jQuery AJAX GET html 数据 IE8 不起作用