Inspecting Fields & Methods

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • You can use the Class object to inspect all methods, fields, and constructors of a class.
  • Methods ending in ...s() (like getMethods()) return an array of all matches.
  • Methods prefixed with Declared... (like getDeclaredMethods()) return private/protected members of this class, but ignore inherited members. Methods without Declared return only public members, but include inherited ones.

Concept

Once you have a Class object, you can query it to discover the structure of the class.

The API distinguishes heavily between “Public Inherited” and “Private Local”:

  • getFields() / getMethods(): Returns all public fields/methods of the class, including those inherited from superclasses (like Object.toString()).
  • getDeclaredFields() / getDeclaredMethods(): Returns all fields/methods (public, protected, private) declared directly in this specific class. It does not include inherited members.

Examples

import java.lang.reflect.*;

class Parent {
    public String publicParentField;
    private String privateParentField;
}

class Child extends Parent {
    public String publicChildField;
    private String privateChildField;
    
    private void secretMethod(int code) { }
}

public class InspectionDemo {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Child.class;
        
        // 1. Inspecting Fields
        System.out.println("--- getFields() ---");
        for (Field f : clazz.getFields()) {
            // Prints: publicChildField, publicParentField
            System.out.println(f.getName()); 
        }
        
        System.out.println("--- getDeclaredFields() ---");
        for (Field f : clazz.getDeclaredFields()) {
            // Prints: publicChildField, privateChildField (Notice Parent is missing!)
            System.out.println(f.getName()); 
        }
        
        // 2. Finding a specific method
        // We must pass the exact name and the parameter types (int.class)
        Method m = clazz.getDeclaredMethod("secretMethod", int.class);
        
        // 3. Inspecting Method properties
        System.out.println("Method Name: " + m.getName());
        System.out.println("Return Type: " + m.getReturnType());
        System.out.println("Is Private? " + Modifier.isPrivate(m.getModifiers()));
    }
}

Interview Questions

Q: How do you get a private field from a superclass using Reflection?
A: This is a tricky scenario. getDeclaredField("privateParentField") on the Child.class will throw a NoSuchFieldException because it only looks at the Child class. To get a private field from a parent, you must traverse up the class hierarchy manually:

Class<?> parentClass = Child.class.getSuperclass();
Field field = parentClass.getDeclaredField("privateParentField");
field.setAccessible(true);

Q: What does the Modifier class do?
A: When you inspect a field or method, you can call getModifiers(), which returns a single int. This integer is a bitmask representing all the access modifiers applied to the element (public, static, final, synchronized, etc.). The java.lang.reflect.Modifier class provides static helper methods like Modifier.isStatic(int modifiers) to decode this bitmask easily.