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

Static Fields: Accessing Class-Level Data

Understand how to read and write static fields by passing null as the instance parameter to Field.get and Field.set.

Static Fields: Accessing Class-Level Data

What You'll Learn

You'll learn how to read and write static fields reflectively by passing null as the instance parameter to Field.get and Field.set.


The Core Idea

Static fields belong to the class itself, not to any particular instance. When you access a regular field reflectively, you pass an object instance to Field.get() or Field.set() because the field's value is stored in that specific object. But static fields don't need an instance—they're shared across the entire class.

Think of it this way: If a regular field is like a personal locker assigned to each student, a static field is like the school's shared bulletin board. You don't need to ask which student to read the bulletin board—it's accessible to everyone at the class level.

When using Reflection API methods like Field.get() and Field.set() with static fields, you simply pass null instead of an object reference. This tells the reflection system, "I'm working with class-level data, not instance-specific data."


Accessing Static Fields

class Configuration {
    public static int maxConnections = 100;
}

// Get the Field object
Field field = Configuration.class.getDeclaredField("maxConnections");

// Read the static field value (pass null for the instance)
int value = (int) field.get(null);
System.out.println(value);  // 100

// Write to the static field (pass null for the instance)
field.set(null, 200);
System.out.println(Configuration.maxConnections);  // 200

Notice that both get(null) and set(null, newValue) use null where you'd normally pass an object instance. This works because static fields aren't tied to any object.


Key Takeaway: When accessing static fields reflectively, pass null as the instance parameter to Field.get() and Field.set(), since static fields belong to the class itself, not to individual instances.