Java Reflection Field Value Set setFieldValue(Object object, String fieldName, Object value)

Here you can find the source of setFieldValue(Object object, String fieldName, Object value)

Description

Convenience method for setting the value of a private object field, without the stress of checked exceptions in the reflection API.

License

Apache License

Parameter

Parameter Description
object Object containing the field.
fieldName Name of the field to set.
value Value to which to set the field.

Declaration

public static void setFieldValue(Object object, String fieldName, Object value) 

Method Source Code


//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();
                }
            }
        }
    }
}

Related

  1. setFieldValue(Object obj, String name, Object value)
  2. setFieldValue(Object object, Field field, Object value)
  3. setFieldValue(Object object, String fieldName, Object fieldValue)
  4. setFieldValue(Object object, String fieldName, Object fieldValue)
  5. setFieldValue(Object object, String fieldName, Object fieldValue)
  6. setFieldValue(Object object, String fieldName, Object value)
  7. setFieldValue(Object object, String fieldName, Object value)
  8. setFieldValue(Object object, String fieldName, Object value)
  9. setFieldValue(Object object, String name, Object value)