Runtime Method Name
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Shiju_Joy
Posted On:   Saturday, April 20, 2002 02:10 AM

Hi,



Is it possible to call a method with the method name at

runtime.
I have the code -----



void mymethod()


{


System.out.println("Hello");


}


public static void main(String a[])


{


String s = "mymethod()";


s;


}



By giving s; it should be able to execute mymethod();



Thanks

Re: Runtime Method Name

Posted By:   radone_piedone  
Posted On:   Saturday, April 20, 2002 05:59 AM

Yes, it is possible, just not as straight forward as you expect it to be. Through reflection, Java allows accessing an

Object's fields, constructors and methods at runtime. So you can create an Object of your Class, retrieve its class and

retrieve a method - given its name and the arguments it takes. I would do it like this:




public static void main(String[] args) {

String s = "mymethod"; // without ()

YourClass yourObject = new YourClass(); // you need an Object to retrieve its Class.

try {

Method method = yourObject.getClass().getDeclaredMethod(s, null);
method.invoke(yourObject, null); // the actual method call

}

catch (Exception ex) {
System.out.println("Error occured while trying to retrieve Method");
ex.printStackTrace();
}
}



This should do it. Notice that the actual name of a method, retrieved using - method.getName() - does not contain () at the end. So when you ask for a method, you should not include them either.
About | Sitemap | Contact