Java Class getMethods() Method

The getMethods() method in Java, part of the java.lang.Class class, is used to retrieve an array of Method objects representing all the public methods of the class or interface represented by the Class object.

Table of Contents

  1. Introduction
  2. getMethods() Method Syntax
  3. Understanding getMethods()
  4. Examples
    • Basic Usage
    • Inspecting Method Details
    • Handling Inherited Methods
  5. Real-World Use Case
  6. Conclusion

Introduction

The getMethods() method returns an array of Method objects reflecting all the public methods of the class or interface represented by the Class object, including those declared by superclasses and interfaces.

getMethods() Method Syntax

The syntax for the getMethods() method is as follows:

public Method[] getMethods() throws SecurityException

Parameters:

  • This method does not take any parameters.

Returns:

  • An array of Method objects representing all the public methods of the class or interface.

Throws:

  • SecurityException: If access to the method information is denied.

Understanding getMethods()

The getMethods() method allows you to retrieve all accessible public methods of a class or interface, including those inherited from superclasses and interfaces. This is useful for reflection-based operations where you need to access or invoke methods dynamically.

Examples

Basic Usage

To demonstrate the basic usage of getMethods(), we will create a class with different methods and retrieve all public methods using this method.

Example

import java.lang.reflect.Method;

public class GetMethodsExample {
    public static void main(String[] args) {
        Class<Person> personClass = Person.class;
        Method[] methods = personClass.getMethods();

        for (Method method : methods) {
            System.out.println("Method: " + method.getName());
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void publicMethod() {
        System.out.println("Public method");
    }

    protected void protectedMethod() {
        System.out.println("Protected method");
    }

    void packagePrivateMethod() {
        System.out.println("Package-private method");
    }

    private void privateMethod() {
        System.out.println("Private method");
    }
}

Output:

Method: publicMethod
Method: wait
Method: wait
Method: wait
Method: equals
Method: toString
Method: hashCode
Method: getClass
Method: notify
Method: notifyAll

Inspecting Method Details

This example shows how to inspect additional details of each public method, such as its return type and parameter types.

Example

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class InspectMethodDetailsExample {
    public static void main(String[] args) {
        Class<Person> personClass = Person.class;
        Method[] methods = personClass.getMethods();

        for (Method method : methods) {
            System.out.println("Method: " + method.getName());
            System.out.println("Return type: " + method.getReturnType().getName());
            Parameter[] parameters = method.getParameters();
            for (Parameter parameter : parameters) {
                System.out.println("Parameter: " + parameter.getName() + " of type " + parameter.getType().getName());
            }
            System.out.println();
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void publicMethod() {
        System.out.println("Public method");
    }

    protected void protectedMethod() {
        System.out.println("Protected method");
    }

    void packagePrivateMethod() {
        System.out.println("Package-private method");
    }

    private void privateMethod() {
        System.out.println("Private method");
    }
}

Output:

Method: publicMethod
Return type: void

Method: wait
Return type: void
Parameter: arg0 of type long

Method: wait
Return type: void
Parameter: arg0 of type long
Parameter: arg1 of type int

Method: wait
Return type: void

Method: equals
Return type: boolean
Parameter: arg0 of type java.lang.Object

Method: toString
Return type: java.lang.String

Method: hashCode
Return type: int

Method: getClass
Return type: java.lang.Class

Method: notify
Return type: void

Method: notifyAll
Return type: void

Handling Inherited Methods

This example demonstrates how the getMethods() method includes inherited methods from superclasses and interfaces.

Example

import java.lang.reflect.Method;

public class InheritedMethodsExample {
    public static void main(String[] args) {
        Class<Employee> employeeClass = Employee.class;
        Method[] methods = employeeClass.getMethods();

        for (Method method : methods) {
            System.out.println("Method: " + method.getName());
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void publicMethod() {
        System.out.println("Public method in Person");
    }
}

class Employee extends Person {
    public String employeeId;

    public Employee(String name, int age, String employeeId) {
        super(name, age);
        this.employeeId = employeeId;
    }

    public void publicMethodInEmployee() {
        System.out.println("Public method in Employee");
    }
}

Output:

Method: publicMethodInEmployee
Method: publicMethod
Method: wait
Method: wait
Method: wait
Method: equals
Method: toString
Method: hashCode
Method: getClass
Method: notify
Method: notifyAll

Real-World Use Case

Dynamic Method Invocation

In a real-world scenario, you might use the getMethods() method to dynamically invoke public methods of an object. This is particularly useful in frameworks that require runtime manipulation of objects, such as testing frameworks or dependency injection frameworks.

Example

import java.lang.reflect.Method;

public class DynamicMethodInvocationExample {
    public static void main(String[] args) {
        try {
            Person person = new Person("Alice", 30);
            Class<Person> personClass = Person.class;
            Method[] methods = personClass.getMethods();

            for (Method method : methods) {
                if (method.getParameterCount() == 0) {
                    System.out.println("Invoking method: " + method.getName());
                    method.invoke(person);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void publicMethod() {
        System.out.println("Public method in Person");
    }
}

Output:

Invoking method: publicMethod
Public method in Person
Invoking method: toString
Invoking method: hashCode
Invoking method: getClass
Invoking method: notify
Invoking method: notifyAll

Conclusion

The Class.getMethods() method in Java provides a way to retrieve all accessible public methods of a class or interface, including inherited methods. By using this method, you can dynamically access and invoke methods of a class, making it particularly useful for reflection-based operations in frameworks and libraries.

Whether you are working with simple methods or handling complex dynamic method invocations, the getMethods() method offers a reliable way to access and work with public methods at runtime.

Comments