Code example for Field

Methods: get, isAccessible, setAccessible

0
        boolean accessible = makeFieldAccessible(field);
 
        //Cannot be extracted to method! 
        T value;
        try { 
            value = (T) field.get(object);
        } catch (IllegalAccessException x) {
            throw new StubException(x);
        } 
 
        returnToOriginalAccessibleState(field, accessible);
        return value;
    } 
 
    private static Field getFieldFromObject(String fieldName, Object object) {
        try { 
            return object.getClass().getField(fieldName);
        } catch (NoSuchFieldException x) {
            throw new StubException(x.getMessage(), x);
        } 
    } 
 
    private static boolean makeFieldAccessible(Field field) {
        boolean accessible= field.isAccessible();
        if (!accessible) {
            field.setAccessible(true);
        } 
 
        return accessible;
    } 
 
    private static void returnToOriginalAccessibleState(Field field, boolean accessible) {
        if (!accessible) {
            field.setAccessible(false);
        } 
    } 
}