Java
Static Fields
Java Reflection
Programming
Java Classes

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.

Browse interview questions

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:

java
1public class ExampleClass {
2    public static int myStaticField = 10;
3}
4
5public class StaticFieldExample {
6    public static void main(String[] args) {
7        System.out.println(ExampleClass.myStaticField);
8    }
9}

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:

  1. Obtain the Class Object: Every class in Java has an associated Class object. Use ExampleClass.class or Class.forName("ExampleClass").
  2. Get All Fields: Use Class.getDeclaredFields() or Class.getFields() to retrieve fields.
  3. Filter for Static Fields: Iterate over the fields, using Modifier.isStatic(field.getModifiers()) to filter for static fields.

Here's a practical example:

java
1import java.lang.reflect.Field;
2import java.lang.reflect.Modifier;
3
4public class StaticFieldRetriever {
5    public static void retrieveStaticFields(Class<?> clazz) {
6        Field[] fields = clazz.getDeclaredFields(); // Retrieve all declared fields
7        System.out.println("Static fields in class " + clazz.getSimpleName() + ":");
8
9        for (Field field : fields) {
10            if (Modifier.isStatic(field.getModifiers())) {
11                System.out.println(" - " + field.getName());
12            }
13        }
14    }
15
16    public static void main(String[] args) {
17        retrieveStaticFields(ExampleClass.class);
18    }
19}

Explanation:

  • Class.getDeclaredFields(): Returns an array of Field objects that reflect all fields declared by the class, including private fields. Unlike getFields(), 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 returns true if it's static.

Summary Table

ActionMethod/PropertyDescription
Obtain Class ObjectExampleClass.classGets Class object for ExampleClass.
Retrieve All Declared FieldsgetDeclaredFields()Fetches all declared fields of a class (private, protected, etc.).
Check if Field is StaticModifier.isStatic(field.getModifiers())Determines whether the field is static.
Filter and Display Static Fieldsif (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:

java
1import java.lang.annotation.Retention;
2import java.lang.annotation.RetentionPolicy;
3
4@Retention(RetentionPolicy.RUNTIME)
5@interface Important {}
6
7public class ConstantClass {
8    @Important
9    public static final int IMPORTANT_CONSTANT = 100;
10    public static final int REGULAR_CONSTANT = 50;
11}
12
13public static void retrieveAnnotatedStaticFields(Class<?> clazz) {
14    for (Field field : clazz.getDeclaredFields()) {
15        if (Modifier.isStatic(field.getModifiers()) && field.isAnnotationPresent(Important.class)) {
16            System.out.println("Annotated static field: " + field.getName());
17        }
18    }
19}
20
21public static void main(String[] args) {
22    retrieveAnnotatedStaticFields(ConstantClass.class);
23}

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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track 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.

Browse interview questions

All Rights Reserved.