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

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

Description

set Field Value

License

Apache License

Declaration

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

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

public class Main {

    public static void setFieldValue(final Object object, final String fieldName, final Object value) {
        Field field = getDeclaredField(object, fieldName);

        if (field == null)
            throw new IllegalArgumentException(
                    "Could not find field [" + fieldName + "] on target [" + object + "]");

        makeAccessible(field);/*  ww  w .  j  ava  2s  .  c  om*/

        try {
            field.set(object, value);
        } catch (IllegalAccessException e) {

        }
    }

    protected static Field getDeclaredField(final Object object, final String fieldName) {
        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                return superClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
            }
        }
        return null;
    }

    protected static void makeAccessible(final Field field) {
        if (!Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
            field.setAccessible(true);
        }
    }
}

Related

  1. setFieldValue(final Object bean, final Field field, final Object value)
  2. setFieldValue(final Object obj, final String fieldName, final Object value)
  3. setFieldValue(final Object object, final String field, final Object value)
  4. setFieldValue(final Object object, final String fieldName, final Object value)
  5. setFieldValue(final Object object, final String fieldName, final Object value)
  6. setFieldValue(Map map, Class cls)
  7. setFieldValue(Object bean, Field field, Object value)
  8. setFieldValue(Object bean, Field field, Object value)
  9. setFieldValue(Object bean, String field, Object value)