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

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

Description

set Field Value

License

Apache License

Declaration

public static boolean setFieldValue(Object target, String fieldName, Object value)
            throws IllegalAccessException 

Method Source Code


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

import java.lang.reflect.Field;

public class Main {
    public static boolean setFieldValue(Object target, String fieldName, Object value)
            throws IllegalAccessException {
        return setFieldValue(target, fieldName, value, false);
    }/* ww  w  . ja  va 2 s .  c o  m*/

    public static boolean setFieldValue(Object target, String fieldName, Object value, boolean traceable)
            throws IllegalAccessException {
        Field field = searchField(target.getClass(), fieldName, traceable);
        if (field != null)
            return setValue(field, target, value);
        return false;
    }

    private static Field searchField(Class c, String targetField, boolean traceable) {
        do {
            Field[] fields = c.getDeclaredFields();
            for (Field f : fields) {
                if (f.getName().equals(targetField)) {
                    return f;
                }
            }
            c = c.getSuperclass();
            traceable = traceable && c != Object.class;
        } while (traceable);

        return null;
    }

    private static boolean setValue(Field field, Object target, Object value) throws IllegalAccessException {
        if (!field.isAccessible())
            field.setAccessible(true);
        field.set(target, value);
        return true;
    }
}

Related

  1. setFieldValue(Object target, Field field, Object value)
  2. setFieldValue(Object target, Object mock, final Field field)
  3. setFieldValue(Object target, String field, Object value)
  4. setFieldValue(Object target, String fieldName, Object fieldValue)
  5. setFieldValue(Object target, String fieldName, Object value)
  6. setFieldValue(Object target, String fieldName, String fieldValue)
  7. setFieldValue(Object target, String fname, Class ftype, Object fvalue)
  8. setFieldValue(String fieldName, int fieldValue, Object board)
  9. setFieldValue(String inField, Object inObject, Object inValue)