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

Open Source License

Declaration

public static void setFieldValue(final Object object, final String fieldName, final Object value)
        throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException 

Method Source Code


//package com.java2s;
//License from project: Open Source 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)
            throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {

        Field field = getDeclaredField(object.getClass(), fieldName);

        makeAccessible(field);//  ww  w. ja  v a  2s  .  c om

        field.set(object, value);
    }

    protected static Field getDeclaredField(final Object object, final String fieldName)
            throws NoSuchFieldException, SecurityException {

        return getDeclaredField(object.getClass(), fieldName);
    }

    @SuppressWarnings({ "rawtypes", "unused" })
    protected static Field getDeclaredField(final Class clazz, final String fieldName)
            throws NoSuchFieldException, SecurityException {

        for (Class superClazz = clazz; superClazz != Object.class; superClazz = superClazz.getSuperclass()) {

            return superClazz.getDeclaredField(fieldName);
        }

        return null;
    }

    public static void makeAccessible(final Field field) {

        if (!Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {

            field.setAccessible(true);
        }
    }
}

Related

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