Java Reflection Field Value Set setFieldValue(Object objectInstance, String fieldName, Object valueToSet)

Here you can find the source of setFieldValue(Object objectInstance, String fieldName, Object valueToSet)

Description

Sets the field value.

License

Open Source License

Parameter

Parameter Description
objectInstance the object instance
fieldName the field name
valueToSet the value to set

Exception

Parameter Description
NoSuchFieldException the no such field exception
IllegalArgumentException the illegal argument exception
IllegalAccessException the illegal access exception

Declaration

public static void setFieldValue(Object objectInstance, String fieldName, Object valueToSet)
        throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException 

Method Source Code


//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    /**//from   ww w  .  ja va 2s.com
     * Sets the field value.
     *
     * @param objectInstance the object instance
     * @param fieldName the field name
     * @param valueToSet the value to set
     * @throws NoSuchFieldException the no such field exception
     * @throws IllegalArgumentException the illegal argument exception
     * @throws IllegalAccessException the illegal access exception
     */
    public static void setFieldValue(Object objectInstance, String fieldName, Object valueToSet)
            throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        if (null == objectInstance)
            return;
        Field fld = getFieldByName(objectInstance.getClass(), fieldName);
        if (fld == null)
            throw new NoSuchFieldException("Field not found: " + fieldName);
        if (!fld.isAccessible())
            fld.setAccessible(true);
        fld.set(objectInstance, valueToSet);

    }

    /**
     * Gets the field by name.
     * @param cls the class to work with
     * @param name the name
     * @return the field by name
     */
    public static Field getFieldByName(Class<?> cls, String name) {

        if (cls == null || cls.isPrimitive())
            return null;

        Field field = null;
        try {
            field = cls.getDeclaredField(name);
        } catch (Exception e) {
        }

        return (field != null) ? field : getFieldByName(cls.getSuperclass(), name);
    }
}

Related

  1. setFieldValue(Object object, String fieldName, Object value)
  2. setFieldValue(Object object, String fieldName, Object value)
  3. setFieldValue(Object object, String fieldName, Object value)
  4. setFieldValue(Object object, String name, Object value)
  5. setFieldValue(Object object, String name, Object value)
  6. setFieldValue(Object pojo, Field field, Object value)
  7. setFieldValue(Object receiver, String fieldName, Object value)
  8. setFieldValue(Object target, Class targetClass, String fieldName, Object value)
  9. setFieldValue(Object target, Field field, Object newValue)