Course contentsShow
← Java
Lesson 2342 of 2,87045. Reflection APIFree lesson

Obtaining Method Objects from Classes

Using getMethod and getDeclaredMethod to retrieve Method objects for invocation from Class instances.

Obtaining Method Objects from Classes

What you'll learn: How to retrieve Method objects from a Class instance so you can inspect or invoke them reflectively.

The Core Idea

Before you can invoke a method reflectively using Method.invoke(), you first need to get a Method object that represents the method you want to call. Java's reflection API provides two key ways to retrieve specific Method objects from a Class:

  • getMethod(String name, Class<?>... parameterTypes) – Retrieves a public method by name and parameter types, searching the class and all inherited public methods
  • getDeclaredMethod(String name, Class<?>... parameterTypes) – Retrieves any method (public, private, protected, or package-private) declared directly in the class, but not inherited methods

Think of this like looking up a contact in your phone: you need to specify both the name and enough information to distinguish between overloaded versions (the parameter types).

How It Works

Class<?> clazz = String.class;

// Get the public concat method that takes a String parameter
Method concatMethod = clazz.getMethod("concat", String.class);

// Get a declared method (even private ones) from the exact class
Method declaredMethod = clazz.getDeclaredMethod("checkBounds", byte[].class, int.class, int.class);

You must provide the exact parameter types as Class objects. For a no-argument method, pass no additional arguments. For primitive types, use int.class, boolean.class, etc.

The difference matters: getMethod() finds public methods anywhere in the inheritance chain, while getDeclaredMethod() only looks at the specific class you're inspecting.

Key Takeaway: Use getMethod(name, paramTypes) to retrieve public methods (including inherited ones) and getDeclaredMethod(name, paramTypes) to access any method declared directly in a class, enabling targeted reflection operations.