Pergunta

Why when i try to invoke the method i get:

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

My code:

Class<?> tWCCamRes = tCLSLoader.loadClass("com.github.sarxos.webcam.WebcamResolution");
Field tVGA = tWCCamRes.getDeclaredField("VGA");

Method tMeth = tVGA.getDeclaringClass().getDeclaredMethod("getSize");
tMeth.invoke(tVGA, (Object[]) null); // Error

In theory I pass the object instance but it failed.

Thanks in advance :)

Foi útil?

Solução

You're calling the method getSize(), using reflection, on an object of type Field (tVGA), instead of calling it on the value of this field, which is of type WebcamResolution.

Assuming that you really need to do this via reflection, the code should be:

Class<?> tWCCamRes = tCLSLoader.loadClass("com.github.sarxos.webcam.WebcamResolution");
Field tVGA = tWCCamRes.getDeclaredField("VGA");
Object vgaFieldValue = tVGA.get(null); // it's a static field, so the argument of get() can be null.

Method tMeth = tVGA.getDeclaringClass().getDeclaredMethod("getSize");
tMeth.invoke(vgaFieldValue);

Outras dicas

You invoke the getSize method on the field tVGA, but the method is declared on com.github.sarxos.webcam.WebcamResolution.

If you want to invoke an instance method you have to pass the instance as the inovke method's first argument.

If the method doesn't take an argument like com.github.sarxos.webcam.WebcamResolution.getSize() Just invoke it this way:

tMeth.invoke(webcamResolutionObj);

But why don't you just use the WebcamResolution enum.

 String enumName = "VGA";
 WebcamResolution wcResolution = WebcamResolution.valueOf(enumName);
 Dimension size = wcResolution.getSize();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top