/** * Returns the value of a given {@link Field} from an {@link Object}. Or null if the {@link * Object} doesn't have a {@link Field} with the given name. * * @param <T> The type of the value * @param object The {@link Object} whose value is being retrieved * @param fieldName The name of the {@link Field} * @return The value of the {@link Field} */ @SuppressWarnings("unchecked") public static <T> T getFieldValue(Object object, String fieldName) { Field field = ReflectionUtils.getField(object.getClass(), fieldName); field.setAccessible(true); try { return (T) field.get(object); } catch (Exception ex) { return null; } }
/** * Set a value in the given object without using getters or setters * * @param object The object where we want to null the expression * @param expression The expression we want to null * @param value The new value to set */ public static void set(Object object, String expression, Object value) { Field field = ReflectionUtils.getField(object.getClass(), expression); field.setAccessible(true); try { field.set(object, value); } catch (SecurityException e) { throw new UnexpectedException(e); } catch (IllegalArgumentException e) { throw new UnexpectedException(e); } catch (IllegalAccessException e) { throw new UnexpectedException(e); } finally { field.setAccessible(false); } }
/** * Returns a {@link Field} from a class or any of its super classes. * * @param clazz The Class whose {@link Field} is looked for * @param fieldName The name of the {@link Field} to get * @return The {@link Field} */ public static Field getField(Class<?> clazz, String fieldName) { try { return clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { // If the field wasn't found in the object class, its superclass must // be checked if (clazz.getSuperclass() != null) { return ReflectionUtils.getField(clazz.getSuperclass(), fieldName); } // If the field wasn't found and the object doesn't have a // superclass, an exception is thrown throw new UnexpectedException( "The class '" + clazz.getName() + "' doesn't have a field named '" + fieldName + "'."); } }