Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to invoke a method from a class which is loaded Dynamically???

 
Murali Obla
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello folks,

I have loaded a class dynamically and I have retrieved the methods under that class.I was trying to invoke those mehtods but it's causing exceptions!!!.
Here is the part of my code
[CODE]
Class obj=Class.forName(cTName);
System.out.println("Class Name "+cName);
Method[] list= obj.getDeclaredMethods();
for(int i=0;i<3;i++)
{
System.out.println("Method "+list[i].getName());
System.out.println("Return Type is "+list[i].getReturnType());
System.out.println("Parameters Required "+list[i].getParameterTypes());
Object methodInvoke = list[i].invoke(obj,null);

}
System.out.println();
[CODE]
I can't understand what getParameterTypes is returning
Folks,Please help me how to invoke the methods???
Thanks in Advance,
Murali
 
sandy gupta
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use the Mthod class in the reflection API.....u have to know the name of the method in order to call it using the same.....
HTH
Sahil
 
Murali Obla
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sahil,

Can u give me some sample code....
Regards,
Murali
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you invoke a method you have to give it the input parameters that the signature requires. When you used list[i].invoke(obj,null); passing the null was the same as saying "invoke the version of this method that takes no parameters. Well - there might not BE such a method. You use the getParameterTypes to create an array containing objects of the correct types to match what the input parameters for that method are.
So you should pass it an array containing objects of the types that you "created" when you called list[i].getParameterTypes());.
So the call should be
Object methodInvoke = list[i].invoke(obj,list[i].getParameterTypes());
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic