Accessing Static Fields

We will use an example to better understand FEST-Reflect's fluent interface for static field access.

Let's assume we have a simple class Person that defines the following field:

class Person {

  private static int count;

}

The following sections compares static field access using Java Reflection and FEST-Reflect. We are going to assume the following static import:

import static org.fest.reflect.core.Reflection.staticField;

Reading the value of a static field

Java Reflection:

Field field = Person.class.getField("count");

AccessController.doPrivileged(new PrivilegedAction<Void>() {
  public Void run() {
    field.setAccessible(true);
    return null;
  }
});    

int count = (int) field.get(null);

FEST-Reflect:

int count = staticField("count").ofType(int.class)
                                .in(Person.class)
                                .get();

Setting the value of a field

Java Reflection:

Field field = Person.class.getField("count");

AccessController.doPrivileged(new PrivilegedAction<Void>() {
  public Void run() {
    field.setAccessible(true);
    return null;
  }
});    

field.set(null, 8);

FEST-Reflect:

staticField("count").ofType(int.class)
                    .in(Person.class)
                    .set(8);