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.


import java.lang.reflect.Method;

/**
 *
 * @author javadb.com
 */

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

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: