Home arrow static arrow Java Programming [Archive] - Run a method retrieved from Class ...
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Run a method retrieved from Class ...
This topic has 4 replies on 1 page.

Posts:43
Registered: 4/1/03
Run a method retrieved from Class ...  
Jun 15, 2004 12:38 AM



 
Hello guys,

is it possible to run a method that I have retrieved from Class getMethods?

Class class = myobject.getClass();
Method[] mymethods= class.getMethods();

for (int i=0;i<mymethods.length;i++) {

if (mymethods.getName().equals("Method I Want to Run")) {
// here I want to run that method....
}

}

Thanks
Let me know...
C.
 

Posts:951
Registered: 6/7/01
Re: Run a method retrieved from Class ...  
Jun 15, 2004 12:41 AM (reply 1 of 4)



 
Just call the invoke method on your Method instance.
 

Posts:1,160
Registered: 7/24/97
Re: Run a method retrieved from Class ...  
Jun 15, 2004 12:44 AM (reply 2 of 4)



 
Says what you have to do in the Method JavaDocs.
Essentially you need an instance that has this method to call on and a, possibly null, array of object references as the parameters
Class clazz = String.class;Method m = clazz.getMethod( "length", null );  System.out.println( m.invoke( "Hello World", null ) );

does the rest.
The reference o is an instance of String, I use the length method to illustrate the invocation.
No exceptions/errors have been taken into account with this code.
 

Posts:43
Registered: 4/1/03
Re: Run a method retrieved from Class ...  
Jun 15, 2004 12:46 AM (reply 3 of 4)



 
Ok thanks.

But my problem is that my method name is in a String because it comes from
a database select.

If you any ideas please let me know.

 

Posts:43
Registered: 4/1/03
Re: Run a method retrieved from Class ...  
Jun 15, 2004 12:48 AM (reply 4 of 4)



 
Ok Thanks andyba!

You have been so fast that I didn't catch your answer.
That's what I need...
 
This topic has 4 replies on 1 page.