Here you can find the source of setFieldValue(Object object, String fieldName, Object value)
Parameter | Description |
---|---|
object | Object in which to set the field. |
fieldName | Name of the field. |
value | Value to which to set the field. |
public static void setFieldValue(Object object, String fieldName, Object value)
//package com.java2s; //License from project: Apache License import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { /**/*from w w w . j a va 2s . c o m*/ * Sets the value of a field in an object. * * @param object * Object in which to set the field. * @param fieldName * Name of the field. * @param value * Value to which to set the field. */ public static void setFieldValue(Object object, String fieldName, Object value) { try { Field field = getDeclaredFieldInHierarchy(object.getClass(), fieldName); if (field == null) { throw new RuntimeException(String.format("Class %s does not have field %s in its hierarchy.", object.getClass(), fieldName)); } field.setAccessible(true); field.set(object, value); } catch (Exception ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException(ex); } } } /** * Returns the field with the given name in the class hierarchy. If multiple * fields with the same name exist in hierarchy, the field in the class * closest to the clazz gets returned. * * @param clazz * class to look for fields in the hierarchy * @param fieldName * fieldName to find in the class */ public static Field getDeclaredFieldInHierarchy(Class<?> clazz, String fieldName) { assert fieldName != null : "fieldName cannot be null"; Field[] fields = getDeclaredFieldsInHierarchy(clazz); for (Field field : fields) { if (fieldName.equals(field.getName())) { return field; } } return null; } /** * Returns an array of all declared fields in the given class and all * super-classes. */ public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) { if (clazz.isPrimitive()) { throw new IllegalArgumentException("Primitive types not supported."); } List<Field> result = new ArrayList<Field>(); while (true) { if (clazz == Object.class) { break; } result.addAll(Arrays.asList(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } return result.toArray(new Field[result.size()]); } }