dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Java
Expertise: Intermediate
May 25, 1999

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Invoking Methods Using Reflection

The java.reflect package enables a Java program to invoke methods on classes using the string names of the methods. This feature is the basis of the interaction between a Java IDE and JavaBeans. To invoke a method on a particular class, obtain a reference to the object on which the method has to be invoked and then obtain the class for the object. Next, obtain an instance of Method for the method's String name. Finally, construct the arguments for the method and invoke it using the invoke() call on the method. This example shows how the method "aMethod" can be called on an object of type "aClass":
 
1. 	  Class aClass = anObject.getClass();
2. 	  Class[] paramTypes = new Class[1];
3. 	  paramTypes[0] = String.class;
4. 	  
5. 	  Method m = null;
6. 	  try {
7. 	    m = aClass.getMethod("confirmMsg", paramTypes);
8.      }
9.      catch (NoSuchMethodException nsme) {
10.    nsme.printStackTrace();
11.   }
12. 	  
13.   Object[] params = new Object[1];
14.   params[0] = "This is a test";
15. 	  
16.   try {
17.     String result = (String)m.invoke(anObject, params);
18.     System.out.println(result);
19.   }
20.   catch (IllegalAccessException iae) {
21.     iae.printStackTrace();
22.   }
23.   catch (InvocationTargetException ite) {
24.     ite.printStackTrace();
25.   }
On Line 1, you obtain the class for the object "anObject". Assume that the program already has a reference to the object here. Lines 2-3 construct the argument types for the method to be invoked. The method takes only one parameter of type String. Then you construct an array of parameter types. On Lines 5-11, you obtain an instance of the method itself. The name of the method is "comfirmMsg". You construct the actual parameters on Lines 13-14. Finally, on Lines 17-18, you call the method and print out the return value.
Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date