我是 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/