Sunday, June 26, 2011

Getting the Method Information of a given class

Hello guys After some time,
All Java Programmers and Developers Know java is a Object Oriented Programming language. Java can be explain with few words, which is "classes and make objects using the class and interact between objects" so every object have the template as their classes.
Here we are going to show how can we get the information of a given class at the run time. To overcome the problem we have to use the Reflection API which is inbuilt with jdk. Reflection is a very useful tool for developers because if we would like to make some changes to our class at runtime it is the most suitable way.
I would like to show a small program which will provide the all methods of a given class at runtime.
import java.lang.reflect.*;
public class MethodsFinder {
  public static void main(String args[]){
         try {
            Class classes = Class.forName(args[0]);
            Method[] methods = classes.getDeclaredMethods(); 
            for (int i = 0; i < methods.length; i++)
         catch (Exception e) {
            System.err.println("Your error is " + e);
   }Save the above code in a notepad, name the notepad as ""
Compile the source file as     "javac"
and run the file by giving your class as argument as java MethodsFinder java.lang.String
the above underline class is my argument therefor It will provide the output as


 The above output shows all the methods of String class which is an inbuilt class in java. We can get the method details of any given classes just by changing the argument at runtime. Ok guys I thing you have got my point and do it yourself.

No comments:

Post a Comment