How can I dynamically invoke a method, where I have the method name in a String?

John Zukowski

Using the Java Reflection API permits you to dynamically invoke methods from string names at a significant performance penalty.

To find the method to invoke, you would create an array of argument types, find the method by name and argument types, create an array of arguments, then invoke the method for an instance of the class:

// Find method(String, int)
Class aClass = ...;
Object parameters[] = {String.class, int.class};
Method method = aClass.getMethod("method", parameters);
// Invoke method(String, int)
Object arguments[] = {"Hello", new Integer(3)};
returnValue = method.invoke(aClassInstance, arguments);

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact