*
The moose likes Java in General and the fly likes Reflection API - Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reflection API - Method" Watch "Reflection API - Method" New topic
Author

Reflection API - Method

vivek ja
Ranch Hand

Joined: Feb 24, 2005
Posts: 80
I have the following code

Class c = Class.forName(newForm.getClass().getName());
Method method1 = c.getMethod("myMethod", parameterTypes);
Object[] obj = new Object []{listOfStudents};
method1 .invoke((Object)c, obj);

Can someone tell me what this method invoke() takes as parameters? I am now giving the class that contains the method, and a list. (the method myMethod takes List as parameter)
I am getting IllegalArgumentException on the method1.invoke line when i run this code currently
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
I think the second parameter is the array of arguments used for the method call. If the method accepts a list, you have to put the list in the array.
Mattias Arthursson
Ranch Hand

Joined: Jul 26, 2004
Posts: 90
The first argument to invoke should be the object instance on which the method is invoked. You are now passing the class object.
should work.


Admit nothing. Blame everyone. Be bitter.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Have you read the API? It states that the first argument to invoke is "the object the underlying method is invoked from" or "If the underlying method is static, then the [first argument] may be null." Also, your first line can be more simply written:

Class c = newForm.getClass();


There is no emoticon for what I am feeling!
vivek ja
Ranch Hand

Joined: Feb 24, 2005
Posts: 80
I just realised that the method myMethod is in the superclass of the newForm class.
I tried writing that line invoke(newForm, obj) and its still giving the same error. If it is there in the superclass, then wont i be able to access it??
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
If the method is defined in a superclass, getMethod will work (see the APIs). Here is a demo. You must be doing something else wrong.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reflection API - Method
 
Similar Threads
Cast Object back to its original type
Reg. invoking private methods
Problem with Class.forName()
question about polymorphism
super of super