Java Reflection Field Set setField(final Object obj, final String variableName, final Object variableValue)

Here you can find the source of setField(final Object obj, final String variableName, final Object variableValue)

Description

Sets variable by reflection down to 3 levels of abstracts classes.

License

Open Source License

Parameter

Parameter Description
obj - object to set the variable on
variableName - name onf the variable to set
variableValue - value of the variable to be set

Declaration

public static void setField(final Object obj, final String variableName, final Object variableValue) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Field;

public class Main {
    /**/*from w w w .  j a va  2  s .c  o m*/
     * Sets variable by reflection down to 3 levels of abstracts classes.
     *
     * @param obj           - object to set the variable on
     * @param variableName  - name onf the variable to set
     * @param variableValue - value of the variable to be set
     */
    public static void setField(final Object obj, final String variableName, final Object variableValue) {
        Field declaredField = null;

        Class<?> clazz = obj.getClass();
        for (int i = 0; i <= 3; i++) {
            try {
                declaredField = clazz.getDeclaredField(variableName);
                break;
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }

        }

        declaredField.setAccessible(true);

        try {
            declaredField.set(obj, variableValue);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

Related

  1. setField(final O object, final String fieldName, final V value)
  2. setField(final Object instance, final String fieldName, final T value)
  3. setField(final Object obj, final String fieldName, final int value)
  4. setField(final Object obj, final String fieldName, final Object value)
  5. setField(final Object obj, final String name, final Object value)
  6. setField(final Object object, final String name, final Object value)
  7. setField(final Object parent, final String name, final Object obj)
  8. setField(java.lang.Object toObj, String tcFieldName, java.lang.Object toNewValue)
  9. setField(Object instance, String fieldName, Object value)