Pergunta

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();
Foi útil?

Solução

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top