Added by Alex Ruiz, last edited by Alex Ruiz on Mar 06, 2009

Labels:

fest fest Delete
reflection reflection Delete
static-method static-method Delete
Enter labels to add to this page:
Wait Image 
Looking for a label? Just start typing.

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 illustrates static method invocation using FEST-Reflect. We will assume the following static import:

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

Without parameters and return type 'void'

Invoking the static method void clearCommon() in Names:

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

With parameters and return type 'void'

Invoking the static method void addCommon(String) in Names:

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

Without parameters and return type other than 'void'

Invoking the static method int sizeOfCommon() in Names:

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

With parameters and return type other than 'void'

Invoking the static method String getCommon(int) in Names:

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

See Also