Java Reference
In-Depth Information
Listing 19.8
Initial implementation of TestingHelper using the reflection API directly
[...]
import java.lang.reflect.Field;
public class TestingHelper {
public static void set( Object object, String fieldName,
Object newValue) {
Field field = getField(object.getClass(), fieldName);
try {
field.set(object, newValue);
} catch (IllegalAccessException e) {
throw new RuntimeException(
"Could not set value of field '" + fieldName +
"' on object " + object + " to " + newValue, e );
}
}
public static <T> T get(Object object, String fieldName) {
Field field = getField(object.getClass(), fieldName);
Object value;
try {
value = field.get(object);
} catch (IllegalAccessException e) {
throw new RuntimeException( "Could not get value of field '" +
fieldName + "' from object " + object, e );
}
@SuppressWarnings("unchecked")
T castValue = (T) value;
return castValue;
}
B
C
D
E
F
G
private static Field getField(Class<?> clazz, String fieldName) {
Class<?> tmpClass = clazz;
do {
for ( Field field : tmpClass.getDeclaredFields() ) {
String candidateName = field.getName();
if ( ! candidateName.equals(fieldName) ) {
continue ;
}
field.setAccessible(true);
return field;
}
tmpClass = tmpClass.getSuperclass();
} while ( clazz != null );
throw new RuntimeException("Field '" + fieldName +
"' not found on class " + clazz);
}
}
This class provides two helper methods B , set() and get() , whose implementation
follows the same workflow: get a reference to a java.lang.reflect.Field C , do some-
thing with it D , and convert E any reflection API exceptions to a RuntimeException so
H
I
J
 
 
 
Search WWH ::




Custom Search