We will use an example to better understand FEST-Reflect's fluent interface for method invocation.
Let's assume we have a simple class Names that defines the following methods:
class Names { private final List<String> names = new ArrayList<String>(); void clear() { names.clear(); } int size() { return names.size(); } void add(String name) { names.add(name); } String get(int index) { return names.get(index); } }
The following sections compares method invocation using Java Reflection and FEST-Reflect. We will assume that
we have the variable 'names' of type Names. We are also going to assume the following
static import:
import static org.fest.reflect.core.Reflection.method;
Java Reflection:
Method method = Names.class.getMethod("clear"); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { method.setAccessible(true); return null; } }); method.invoke(names);
FEST-Reflect:
method("clear").in(names).invoke();
Java Reflection:
Method method = Names.class.getMethod("add", String.class); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { method.setAccessible(true); return null; } }); method.invoke(names, "Yoda");
FEST-Reflect:
method("add").withParameterTypes(String.class) .in(names) .invoke("Yoda");
Java Reflection:
Method method = Names.class.getMethod("size"); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { method.setAccessible(true); return null; } }); int size = (Integer) method.invoke(names);
FEST-Reflect:
int size = method("size").withReturnType(int.class) .in(names) .invoke();
Java Reflection:
Method method = Names.class.getMethod("get", int.class); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { method.setAccessible(true); return null; } }); String name = (String) method.invoke(names, 8);
FEST-Reflect:
String name = method("get").withReturnType(String.class) .withParameterTypes(int.class) .in(names) .invoke(8);