Friday, May 4, 2012

JAVA Reflection : Reading method by reflection

Hi Folks,

      Last week while writing mapping utility, I came across requirement to invoke method on object using method name obviously I decided to use reflection. While using reflection  I came across two methods in java.lang.Class viz.:
    public Method getMethod(String name, Class... parameterTypes)
    public Method getDeclaredMethod(String name, Class... parameterTypes)
   
Though both the methods can be used to retrieve method information dynamically, they behave differently while searching

getMethod
  public Method getMethod(String name,Class... parameterTypes)
              throws NoSuchMethodException, SecurityException
           This method return Method object represented by parameter. The algorithm used for Searching method name, will search the method in Class passed as argument, if the method was not found inside it the search is carried out on all its super classes.

getDeclaredMethod      
 public Method getDeclaredMethod(String name,
                                 Class... parameterTypes)
                throws NoSuchMethodException, SecurityException 
             This method return Method object represented by searching in Class only which is provided as argument.

Note: If you use getMethods in the program instead of getDeclaredMethods, you can also obtain information for inherited methods.

Reference:
http://java.sun.com/developer/technicalArticles/ALT/Reflection/

No comments: