Here you can find the source of setFieldValue(Object object, String fieldName, Object value)
Parameter | Description |
---|---|
object | Object containing the field. |
fieldName | Name of the field to set. |
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; public class Main { /**/*from ww w. j a va 2 s.c o m*/ * Convenience method for setting the value of a private object field, * without the stress of checked exceptions in the reflection API. * * @param object * Object containing the field. * @param fieldName * Name of the field to set. * @param value * Value to which to set the field. */ public static void setFieldValue(Object object, String fieldName, Object value) { try { getDeclaredFieldInHierarchy(object.getClass(), fieldName).set(object, value); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static Field getDeclaredFieldInHierarchy(Class<?> clazz, String fieldName) { while (true) { try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchFieldException e) { if (clazz == Object.class) { throw new RuntimeException(e); } else { clazz = clazz.getSuperclass(); } } } } }