Print/list all methods/functions of class in java (example)

By | March 22, 2017
  • Given a class in java containing public,private & protected methods.
  • Get/list/print all methods of class using class Class.
    • We will use getDeclaredMethods() of Class to retrieve all methods.
Method Name Description
Method[] getDeclaredMethods() Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

1. Program: print/list all methods/functions of class in java (example)

package org.learn.classes;

import java.lang.reflect.Method;

class Person {
    private String name;
    private String age;
    private float salary;

    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

    public float getSalary() {
        return salary;
    }
}

public class DemoListAllMethodsOfClass {
    public static void main(String[] args) {
        Method[] methods = Person.class.getDeclaredMethods();
        int nMethod = 1;
        System.out.println("1. List of all methods of Person class");
        for (Method method : methods) {
            System.out.printf("%d. %s", ++nMethod, method);
            System.out.println();
        }
        System.out.printf("%d. End - all  methods of Person class", ++nMethod);
    }
}

2. Output: print/list all methods/functions of class in java (example)

 1. List of all methods in a Person class
2. public java.lang.String org.learn.classes.Person.getName()
3. public void org.learn.classes.Person.setName(java.lang.String)
4. public void org.learn.classes.Person.setAge(java.lang.String)
5. public float org.learn.classes.Person.getSalary()
6. End - all  methods in a Person class