Retrieve only static fields declared in Java class
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In Java, understanding and retrieving static fields are essential for tasks such as reflection, code analysis, or dynamic configuration. Static fields are class-level variables shared among all instances of a class. This set of shared fields is often used for constants or configuration data that should remain consistent across all instances of the class.
In this article, we'll explore how to retrieve only static fields declared in a Java class using reflection, delve into technical nuances, and provide detailed examples.
Understanding Static Fields in Java
Static fields are part of the class structure rather than associated with specific instances. They are declared using the static keyword, signifying that they belong to the class and not to any particular object.
Key Characteristics of Static Fields:
- Shared Across Instances: All objects of a class share a single copy of the static field.
- Memory Sharing: Static fields reside in the class area of the heap, not in the instance-specific area.
- Access: They can be accessed using the class name directly or through an instance (though the former is recommended).
- Lifetime: Exist for the lifetime of the application or class.
Here's an example of how a static field is declared and initialized in a Java class:
Retrieving Static Fields Using Reflection
Java Reflection API provides capabilities to inspect classes, methods, fields, and other reflective features at runtime. To retrieve static fields from a class, you'll perform the following steps:
- Obtain the
ClassObject: Every class in Java has an associatedClassobject. UseExampleClass.classorClass.forName("ExampleClass"). - Get All Fields: Use
Class.getDeclaredFields()orClass.getFields()to retrieve fields. - Filter for Static Fields: Iterate over the fields, using
Modifier.isStatic(field.getModifiers())to filter for static fields.
Here's a practical example:
Explanation:
- Class.getDeclaredFields(): Returns an array of
Fieldobjects that reflect all fields declared by the class, including private fields. UnlikegetFields(), it does not return fields declared only in superclasses. - Modifier.isStatic(int mod): Takes an integer representing field modifiers (i.e., access modifier,
static,final) and returnstrueif it'sstatic.
Summary Table
| Action | Method/Property | Description |
| Obtain Class Object | ExampleClass.class | Gets Class object for ExampleClass. |
| Retrieve All Declared Fields | getDeclaredFields() | Fetches all declared fields of a class (private, protected, etc.). |
| Check if Field is Static | Modifier.isStatic(field.getModifiers()) | Determines whether the field is static. |
| Filter and Display Static Fields | if (Modifier.isStatic(...)) | Filters fields to print only static ones. |
Additional Details and Considerations
- Static Block Initialization: Often, static fields are initialized within a static block, executed once when the class is loaded.
- Thread-Safety: When accessing static fields from multiple threads, ensure they are modified with synchronized access if necessary to prevent inconsistent states.
- Performance Implications: Reflection could introduce overhead, and therefore it should be used judiciously, especially in performance-oriented applications.
Retrieving Static Constants Using Annotations
Java classes may also contain static constants that are annotated for specific purposes. In such cases, filtering static fields based on annotations can further narrow down to required fields. Here is how you could achieve it:
This code demonstrates how retrieval of static fields can be further refined by considering custom annotations, illustrating the flexibility provided by the reflection API.
Understanding and working with static fields in Java unlocks powerful capabilities in crafting robust applications, especially when leveraging reflection for dynamic behaviors. Using the above techniques, developers can effectively manage and utilize static fields across various scenarios in their Java applications.
Related reading
- Retrieve version from maven pom.xml in code
- Retrieving a List from a java.util.stream.Stream in Java 8
- Retrieving number of unacknowledged messages in RabbitMQ queue from Java/ Spring
- Retrieving the inherited attribute names/values using Java Reflection
- Retrofit 2.0 how to get deserialised error response.body
- Retry policy in CompletionService
- Return collection as read-only
- Return HTTP code 200 from Spring REST API

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.