Java Reflection Field Set setField(Class clazz, T instance, String fieldName, Object value)

Here you can find the source of setField(Class clazz, T instance, String fieldName, Object value)

Description

Set the field of a given object to a new value with reflection.

License

Open Source License

Parameter

Parameter Description
clazz The class of the object
instance The instance to modify (pass null for static fields)
fieldName The field name
value The value to set the field to

Declaration

public static <T> void setField(Class<T> clazz, T instance, String fieldName, Object value) 

Method Source Code


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

import java.lang.reflect.Field;

import static java.lang.String.format;

public class Main {
    /**/*from w ww .  j a va  2 s .  c  o m*/
     * Set the field of a given object to a new value with reflection.
     *
     * @param clazz The class of the object
     * @param instance The instance to modify (pass null for static fields)
     * @param fieldName The field name
     * @param value The value to set the field to
     */
    public static <T> void setField(Class<T> clazz, T instance, String fieldName, Object value) {
        try {
            Field field = getField(clazz, instance, fieldName);
            field.set(instance, value);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(format("Could not set value to field '%s' for instance '%s' of class '%s'",
                    fieldName, instance, clazz.getName()), e);
        }
    }

    private static <T> Field getField(Class<T> clazz, T instance, String fieldName) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(format("Could not get field '%s' for instance '%s' of class '%s'", fieldName,
                    instance, clazz.getName()), e);
        }
    }
}

Related

  1. setField(Class clazz, Object instance, String field, Object value)
  2. setField(Class clazz, Object obj, String fieldName, Object value)
  3. setField(Class ownerClass, Object owner, String fieldName, Object newValue)
  4. setField(Class target, Class fieldType, int index, Object obj, Object value)
  5. setField(Class clazz, T instance, String fieldName, Object value)
  6. setField(Field f, Object instance, Object value)
  7. setField(Field f, Object this_, Object value)
  8. setField(Field field, @Nullable Object instance, Object thing)
  9. setField(Field field, Object classWithField, Object value)