Accessing Fields

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

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

class Person {

  private String name;

}

The following sections compares field access using Java Reflection and FEST-Reflect. We will assume that we have the variable 'person' of type Person. We are also going to assume the following static import:

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

Reading the value of a field

Java Reflection:

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

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

String name = (String) field.get(person);

FEST-Reflect:

String name = field("name").ofType(String.class)
                           .in(person)
                           .get();

Setting the value of a field

Java Reflection:

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

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

field.set(person, "Leia");

FEST-Reflect:

field("name").ofType(String.class)
             .in(person)
             .set("Leia");