Monday, October 10, 2011

List methods of a class using Reflection


In this example we use the Reflection api to obtain the methods of a particular class called Person, which is an inner class. First we need to get the Class object and we do so by calling 'Person.class'. Once we have the Class object we can use it to call the getDeclaredMethods() method which will return an array of type Method.To find out the names of the methods that the Person class contains we simply loop through the array and call getName() for each Method object.

Package org.best.example;
import java.lang.reflect.Method;


public class Main {
   
    /**
     * Lists the methods of a class using the Reflection api.
     */
    public void listMethodsUsingReflection() {

        //Obtain the Class instance
        Class personClass = Person.class;
       
        //Get the methods
        Method[] methods = personClass.getDeclaredMethods();
       
        //Loop through the methods and print out their names
        for (Method method : methods) {
            System.out.println(method.getName());
        }
    }
   
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().listMethodsUsingReflection();
    }
   
   
    class Person {

private String firstname;
        private String lastname;
        private String age;

        public String getFirstname() {
            return firstname;
        }

        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }

        public String getLastname() {
            return lastname;
        }

        public void setLastname(String lastname) {
            this.lastname = lastname;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }
    }
}

If you run the example code above the output will be:

getFirstname
setFirstname
getLastname
setLastname
getAge
setAge

No comments: