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

Inspecting Modifiers: public, private, static, final

Use getModifiers() and the Modifier class to check access levels and other modifiers on members.

Inspecting Modifiers: public, private, static, final

You'll learn how to programmatically check access levels and modifiers on class members using reflection.

The Core Idea

When you inspect fields, methods, or constructors via reflection, you often need to know how they're declared—are they public or private? static or instance-level? final or mutable? Java's Reflection API provides getModifiers() on Field, Method, and Constructor objects, which returns an integer encoding all modifiers. The Modifier class then decodes this integer with static helper methods.

How It Works

Think of modifiers as flags packed into a single integer—like a binary bitmask. Calling getModifiers() retrieves this packed value, and Modifier methods like isPublic(), isPrivate(), isStatic(), and isFinal() check specific bits:

Class<?> clazz = String.class;
Method[] methods = clazz.getDeclaredMethods();

for (Method method : methods) {
    int modifiers = method.getModifiers();
    
    if (Modifier.isPublic(modifiers)) {
        System.out.println(method.getName() + " is public");
    }
    if (Modifier.isStatic(modifiers)) {
        System.out.println(method.getName() + " is static");
    }
    if (Modifier.isFinal(modifiers)) {
        System.out.println(method.getName() + " is final");
    }
}

You can also convert the entire modifier set to a human-readable string:

System.out.println(Modifier.toString(modifiers)); // "public static final"

This technique works identically for Field and Constructor objects—just call getModifiers() and pass the result to Modifier static methods.

Key Takeaway: Use getModifiers() to retrieve a member's modifier integer, then use Modifier.isPublic(), isPrivate(), isStatic(), isFinal(), and similar methods to check specific access levels and properties programmatically.