Get value of a public static field via reflection
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Java, a public static field belongs to the class, not to an instance. Reflection lets you discover that field at runtime and read its value dynamically, which is useful in frameworks, plugin systems, and generic utilities.
The Basic API
The two reflection types you need are Class and Field. For a public static field:
- Obtain the
Classobject. - Look up the field by name.
- Read the field with
get(null).
Passing null is the important detail. Static fields do not require an instance, so the receiver argument is ignored.
Output:
getField Versus getDeclaredField
Use getField when the field is public. It searches public members, including inherited ones. Use getDeclaredField when you specifically want a field declared on that exact class, regardless of visibility.
For the title question, getField is usually the cleanest answer:
If the field type is primitive, the reflection API also offers typed accessors such as getInt, getLong, and getBoolean.
Checking Modifiers Explicitly
If you are writing a generic utility, verify that the field is really public and static before reading it. That prevents confusing runtime errors later.
That kind of guard makes reflection code less fragile and easier to debug.
Initialization Behavior
Reading a static field can trigger class initialization if the class has not been initialized yet. Usually that is fine, but it matters if static initialization has side effects, such as opening files or registering services.
In other words, reflection is not just metadata lookup. It can influence program execution.
Common Pitfalls
The most common mistake is calling field.get(instance) out of habit. For a static field, field.get(null) is the correct and conventional form.
Another mistake is using getDeclaredField and forgetting that it does not search inherited public fields. If the field comes from a superclass or interface, getField is more appropriate.
A third issue is swallowing reflection exceptions. NoSuchFieldException usually means the name is wrong or the lookup method is wrong. IllegalAccessException suggests visibility rules are involved. Those errors are informative and should not be hidden behind a vague catch block.
Finally, avoid reflection when direct access is simpler. Reflection trades compile-time safety for runtime flexibility, so it should solve a real dynamic problem rather than add indirection for no benefit.
Summary
- Read a public static field with
Class.getFieldandField.get(null). - Use typed getters such as
getInt(null)for primitive fields when helpful. - Prefer
getFieldfor inherited public members andgetDeclaredFieldfor exact declared members. - Check modifiers explicitly in reusable utilities.
- Remember that reflective access can trigger class initialization and runtime exceptions.

