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

Field Modifiers: Checking Accessibility and Mutability

Learn how Field.getModifiers reveals field properties like public, static, final, and transient using Modifier class constants.

Field Modifiers: Checking Accessibility and Mutability

What you'll learn: How to use Field.getModifiers() to inspect field properties like public, static, final, and transient at runtime using the Modifier class.

Understanding Field Modifiers

When working with reflection, you often need to know a field's properties before accessing or modifying it. Is it public or private? Is it static? Is it final and therefore immutable? The Field class provides getModifiers(), which returns an integer encoding all the field's modifiers as bit flags.

Think of it like a field's identity card—encoded information that tells you everything about its access level and special properties.

Reading Modifiers with the Modifier Class

The Modifier class provides constants and static methods to decode these bit flags. Here's how you check specific modifiers:

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

class Example {
    public static final int MAX = 100;
    private transient String temp;
}

Field maxField = Example.class.getField("MAX");
int mods = maxField.getModifiers();

boolean isPublic = Modifier.isPublic(mods);      // true
boolean isStatic = Modifier.isStatic(mods);      // true
boolean isFinal = Modifier.isFinal(mods);        // true

Field tempField = Example.class.getDeclaredField("temp");
int tempMods = tempField.getModifiers();

boolean isPrivate = Modifier.isPrivate(tempMods);     // true
boolean isTransient = Modifier.isTransient(tempMods); // true

Why This Matters

Before attempting setAccessible() or set(), you can check if a field is final to avoid runtime errors. You can verify whether a field is static to decide whether you need a target object. You can inspect transient to understand serialization behavior.

Key Takeaway: Use Field.getModifiers() combined with Modifier class methods (isPublic, isStatic, isFinal, etc.) to programmatically inspect field properties and make informed decisions about reflective access and modification.