Ejemplo n.º 1
0
 /**
  * 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;
   }
 }
Ejemplo n.º 2
0
 /**
  * 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);
   }
 }
Ejemplo n.º 3
0
  /**
   * 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 + "'.");
    }
  }
Ejemplo n.º 4
0
 public static void setId(Identifiable identifiable, Long id) {
   ReflectionUtils.set(identifiable, "id", id);
 }