Java Reference
In-Depth Information
19.5.3
FEST-Reflect
FEST
-Reflect offers helper classes to access all sorts of Java entities, such as fields, meth-
ods, constructors, and even inner classes. And as is the case with all other
FEST
mod-
ules, it follows the fluent interface approach, this time using
org.reflect.core.
Reflection
as the entry point. For instance, to create an instance of a
User
object, you
use the
constructor()
method:
User user = Reflection.constructor().in(User.class).newInstance();
Behind the scenes,
constructor()
returns a
TargetType
object, whose method
in()
returns an
Invoker
, which in turn creates the actual
User
instance through the
new-
Instance()
method. All these methods use parameterized arguments and return val-
ues (similar to the
get()
method in listing 19.9), so the result can be used without an
explicit cast. The only catch is that most of the time you must pass the expected class as
a parameter somewhere in the chain; for instance, to use
FEST
to set our
DAO
, it would
be necessary to explicitly indicate that the field is of type
UserDao
, as shown here:
Reflection.field("userDao").ofType(UserDao.class).in(facade).set(dao);
Because of such requirements,
TestingHelper
couldn't be rewritten using
FEST
with-
out changing its signature to include the field class (as shown in listing 19.10), which
would also require a change in the
set
DAO
statement:
TestingHelperFESTReflect.set(facade, "userDao", UserDao.class, dao);
Listing 19.10
TestingHelper
refactored to use FEST-Reflect
[...]
import
org.fest.reflect.core.Reflection;
public class
TestingHelperFESTReflect {
public static
<T> void set(Object object, String fieldName,
Class<T> fieldClass, T newValue) {
Reflection.field(fieldName).ofType(fieldClass).in(object).set(newValue);
}
public static
<T> T get(Object object, String fieldName,
Class<T> fieldClass) {
return
Reflection.field(fieldName).ofType(fieldClass).in(object).get();
}
}
Given these two alternatives, the choice again depends on personal style:
FEST
-
Reflect is more powerful and follows a more natural syntax than its
JU
nit-addons
counterpart, at the cost of being more complex (its syntax is less natural for develop-
ers who are not used to it) and requiring one more piece of information (the type of
the field being accessed).