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

Apache License

Declaration

public static void setFieldValue(final Object object, final String fieldName, final 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(final Object object, final String fieldName, final Object value) {
        @SuppressWarnings("rawtypes")
        Class clazz = object.getClass();
        try {/*  w ww  . j a  v a2s .  co  m*/
            getAccessibleField(clazz, fieldName).set(object, value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static Field getAccessibleField(@SuppressWarnings("rawtypes") final Class clazz, final String fieldName)
            throws NoSuchFieldException {
        Class<?> tmpClass = clazz;
        do {
            for (final Field field : tmpClass.getDeclaredFields()) {
                String candidateName = field.getName();
                if (!candidateName.equals(fieldName)) {
                    continue;
                }
                field.setAccessible(true);
                return field;
            }
            tmpClass = tmpClass.getSuperclass();
        } while (clazz != null);

        throw new RuntimeException("Field '" + fieldName + "' not found on class " + clazz);
    }
}

Related

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