Invoking Static Methods

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

Let's assume we have a simple class Names that defines the following methods:

class Names {

  private static final List<String> COMMON_NAMES = new ArrayList<String>();

  static void clearCommon() {
    COMMON_NAMES.clear();
  }

  static int sizeOfCommon() {
    return COMMON_NAMES.size();
  }

  static void addCommon(String name) {
    COMMON_NAMES.add(name);  
  }

  static String getCommon(int index) {
    return COMMON_NAMES.get(index);
  }  

}

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

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

Invoking static methods without parameters and return type 'void'

Java Reflection:

Method method = Names.class.getMethod("clearCommon");

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

method.invoke(null);

FEST-Reflect:

staticMethod("clear").in(Names.class).invoke();

Invoking static methods with parameters and return type 'void'

Java Reflection:

Method method = Names.class.getMethod("addCommon", String.class);

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

method.invoke(null, "Frodo");

FEST-Reflect:

staticMethod("addCommon").withParameterTypes(String.class)
                         .in(Names.class)
                         .invoke("Frodo");

Invoking static methods without parameters and return type other than 'void'

Java Reflection:

Method method = Names.class.getMethod("sizeOfCommon");

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

int size = (Integer) method.invoke(null);

FEST-Reflect:

int size = staticMethod("sizeOfCommon").withReturnType(int.class)
                                       .in(Names.class)
                                       .invoke();

Invoking static methods with parameters and return type other than 'void'

Java Reflection:

Method method = Names.class.getMethod("getCommon", int.class);

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

String name = (String) method.invoke(null, 8);

FEST-Reflect:

String name = staticMethod("getCommon").withReturnType(String.class)
                                       .withParameterTypes(int.class)
                                       .in(Name.class)
                                       .invoke(8);