Setting fields

We can also call setAccessible on Field objects and then we can even set the value of private fields using reflection. Without further fake stories, just for the sake of the example, let's make a ConsistencyChecker named SettableChecker:

@Component 
@PoweredDevice
public class SettableChecker implements ConsistencyChecker {
private static final Logger log = LoggerFactory.getLogger(SettableChecker.class);

private boolean setValue = false;

public boolean isInconsistent(Order order) {
return setValue;
}
}

This checker will return false, unless we set the field to true using reflection. We do set it as such. We create a method in the Checker class and invoke it from the checking process for each checker:

private void setValueInChecker(ConsistencyChecker checker) { 
Field[] fields = checker.getClass().getDeclaredFields();
for( final Field field : fields ){
if( field.getName().equals("setValue") &&
field.getType().equals(boolean.class)){
field.setAccessible(true);
try {
log.info("Setting field to true");
field.set(checker,true);
} catch (IllegalAccessException e) {
log.error("SNAFU",e);
}
}
}
}

The method goes through all the declared fields and if the name is setValue and the type is boolean, then it sets it to true. This will essentially render all orders that contain a powered device as rejected.

Note that although boolean is a built-in language primitive, which is not a class by any means, it still has a class so that reflection can compare the type of the field gainst he class that boolean artificially has. Now boolean.class is a class literal in the language, and for each primitive, a similar constant can be used. The compiler identifies these as class literals and creates the appropriate pseudo class references in the byte code so that primitives can also be checked in this way, as demonstrated in the sample code of the setValueInChecker method.

We checked that the field has the appropriate type, and we also called the setAccessible method on the field. Even though the compiler does not know that we really did everything to avoid IllegalAccessException, it still believes that calling set on field can throw such an exception, as it is declared. However, we know that it should not happen. (Famous last words of a programmer?) To handle this situation, we surround the method call with a try block, and in the catch branch, we log the exception.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.176.72