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


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

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
Thanks for your registration, follow us on our social networks to keep up-to-date