File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reflection API - Method

 
vivek ja
Ranch Hand
Posts: 80
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 90
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
 
vivek ja
Ranch Hand
Posts: 80
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1780
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic