public static <E> E getFieldValue(Object instance, String fieldName) { checkNotNull(instance, "Object to retrieve field from can't be null"); Field field; Class<?> clazz = instance.getClass(); try { field = clazz.getDeclaredField(fieldName); field.setAccessible(true); } catch (Exception e) { throw new ReflectionException(e); } return getFieldValue0(instance, field, clazz.getName(), fieldName); }
public static <E> E getFieldValue(Object instance, String fieldName) { checkNotNull(instance, "Object to retrieve field from can't be null"); Field field; Class<?> clazz = instance.getClass(); try { field = clazz.getDeclaredField(fieldName); field.setAccessible(true); } catch (Exception e) { throw new ReflectionException(e); } return getFieldValue0(instance, field, clazz.getName(), fieldName); }
/** * Gets the value for a static field. * * @param clazz class which contains the field * @param fieldName name of the field * @param fieldType type of the field * @param <E> type of the field * @return the value of the static field */ public static <E> E getStaticFieldValue(Class clazz, String fieldName, Class fieldType) { Field field = getField(clazz, fieldName, fieldType); if (field == null) { throw new ReflectionException(format("Field %s.%s is not found", clazz.getName(), fieldName)); } field.setAccessible(true); return getFieldValue0(null, field, clazz.getName(), fieldName); }
/** * Gets the value for a static field. * * @param clazz class which contains the field * @param fieldName name of the field * @param fieldType type of the field * @param <E> type of the field * @return the value of the static field */ public static <E> E getStaticFieldValue(Class clazz, String fieldName, Class fieldType) { Field field = getField(clazz, fieldName, fieldType); if (field == null) { throw new ReflectionException(format("Field %s.%s is not found", clazz.getName(), fieldName)); } field.setAccessible(true); return getFieldValue0(null, field, clazz.getName(), fieldName); }
private static Object findTargetObject(Object parent, String property, String[] path) { for (int i = 0; i < path.length - 1; i++) { Class<?> clazz = parent.getClass(); String fieldName = path[i]; Field field = findField(clazz, fieldName); if (field == null) { if (i == 0) { // we have no match at all return null; } else { // we found at least one item in the path throw new BindException( format("Failed to find field [%s.%s] in property [%s]", clazz.getName(), fieldName, property)); } } Object child = getFieldValue0(parent, field, clazz.getName(), property); if (child == null) { try { child = field.getType().newInstance(); field.set(parent, child); } catch (InstantiationException e) { throw new BindException(format("Failed to initialize null field '%s'", field), e); } catch (IllegalAccessException e) { throw new BindException(format("Failed to initialize null field '%s'", field), e); } } parent = child; } return parent; }