Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reflection API: Simple method invocation problems  RSS feed

 
Neil Robinson
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
i'm trying to invoke a simple method:
public class test {
public void testMethod() {
System.out.println("testMethod called...");
}
}
using:
Class c = loadClass(name);
Method m = c.getMethod("testMethod", null);
try {
m.invoke(new Object(), null);
} catch (Exception e) {
e.printStackTrace();
}
but I get:
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at JarClassLoader.invokeClass(JarClassLoader.java:62)
at JarRunner.main(JarRunner.java:42)
the method is found (i've set attribute 'Main-Class' in the manifest) but
the exception is thrown when I try to invoke the method. I'm having
difficulty understanding how to use the m.invoke(.) method. What exactly
do I need to put in as the first argument in this instance?
Thanks in advance
 
Joe Ess
Bartender
Posts: 9406
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are having trouble with a method you should look at the Java Documentation. Looking at the documentation for the class
java.lang.reflect.Method, in particular, the method invoke(), it says:

Parameters:
obj - the object the underlying method is invoked from
args - the arguments used for the method call

The exception you are getting is:

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

I'd say you need to pass an instance of test rather than Object.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!