- Given a class in java containing public,private & protected methods.
- We will declare a Person class containing:
- Public methods.
- Private methods and
- Protected methods.
- We will print all methods of Person 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: List all 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;
}
private void setName(String name) {
this.name = name;
}
protected 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 all methods of class in java (example)
1. List of all methods of Person class
2. public java.lang.String org.learn.mk.ref.Person.getName()
3. private void org.learn.mk.ref.Person.setName(java.lang.String)
4. protected void org.learn.mk.ref.Person.setAge(java.lang.String)
5. public float org.learn.mk.ref.Person.getSalary()
6. End - all methods of Person class