0

I am new in ClassLoader issue in Java. So how can i call methods like

getDefault().GetImage();

This is my current code:

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);

EDIT:

I tried this:

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);

But I get:

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

I need to get this result:

BufferedImage tBuffImage = Webcam.getDefault().getImage();
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
SamYan
  • 1,553
  • 1
  • 19
  • 38

1 Answers1

1

You cannot do this, this is not how reflection works.

You need to split your String by . and then loop and invoke methods in turn.

This ought to work

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;
}

A quick test:

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));
}

Output:

Greenwich Mean Time
Greenwich Mean Time
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • A class cannot be static, a method can be static. This should still work in that case, from the [JavaDoc](http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object...)) _If the underlying method is static, then the specified obj argument is ignored. It may be null._ – Boris the Spider Jul 27 '13 at 23:03