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

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

Description

set Field Value

License

Apache License

Declaration

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

Method Source Code


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

import java.lang.reflect.Field;

public class Main {

    public static void setFieldValue(Object object, String fieldName, Object value) {
        Field field = getAccessibleField(object, fieldName);
        if (field == null) {
            throw new IllegalArgumentException("Could not find field " + fieldName);
        }/*from   w  w  w.  j  a  va  2s.com*/
        try {
            field.set(object, value);
        } catch (IllegalAccessException e) {

        }
    }

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

Related

  1. setFieldValue(Object object, Field field, Object value)
  2. setFieldValue(Object object, String fieldName, Object fieldValue)
  3. setFieldValue(Object object, String fieldName, Object fieldValue)
  4. setFieldValue(Object object, String fieldName, Object fieldValue)
  5. setFieldValue(Object object, String fieldName, Object value)
  6. setFieldValue(Object object, String fieldName, Object value)
  7. setFieldValue(Object object, String fieldName, Object value)
  8. setFieldValue(Object object, String name, Object value)
  9. setFieldValue(Object object, String name, Object value)