Getting Declared Methods: Class-Specific Methods Only
You'll learn how to retrieve only the methods defined directly in a specific class, including private ones, without any inherited methods.
The Difference Between getMethods() and getDeclaredMethods()
While getMethods() gives you all public methods including those inherited from parent classes and interfaces, getDeclaredMethods() takes a different approach: it returns only the methods declared directly in the class you're inspecting, regardless of their access level (public, protected, private, or package-private).
Think of it like looking at a class's resume versus its entire family tree. getMethods() shows you everything the class can do, including skills inherited from ancestors. getDeclaredMethods() shows only what this specific class brings to the table—its own unique declarations.
Why This Matters
This is crucial when you need to:
- Examine the class's own implementation details
- Access private helper methods via reflection
- Distinguish between inherited and class-specific behavior
- Build tools that analyze code structure
Key Characteristics
getDeclaredMethods() returns:
- All access levels: public, protected, private, and package-private methods
- Only declared methods: nothing inherited from superclasses
- No interface methods: unless the class itself declares them
Class<?> clazz = String.class;
Method[] declaredMethods = clazz.getDeclaredMethods();
// Returns only methods declared in String.class itself
// Includes private helpers like checkBounds() or indexOfNonWhitespace()
// Excludes methods inherited from Object like toString() (unless String overrides it)
Key Takeaway: Use getDeclaredMethods() when you need to inspect only the methods defined directly within a specific class, including private ones, without any inherited baggage.