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

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

Description

Sets the field of the given class.

License

Open Source License

Parameter

Parameter Description
clazz the class on which the field is declared
fieldName the field name
instance the instance to set the field on (null for static fields)
value the value to set
T the instance's type

Declaration

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

Method Source Code

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

import java.lang.reflect.Field;

public class Main {
    /**//  ww  w .  j a  v a 2 s.com
     * Sets the field of the given class.
     *
     * @param clazz the class on which the field is declared
     * @param fieldName the field name
     * @param instance the instance to set the field on (null for static fields)
     * @param value the value to set
     * @param <T> the instance's type
     */
    public static <T> void setField(Class<? super T> clazz, String fieldName, T instance, Object value) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(instance, value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new IllegalStateException("Could not set field '" + fieldName + "' on " + instance, e);
        }
    }
}

Related

  1. setField(Class clazz, Object src, String fieldName, Object value)
  2. setField(Class clazz, String name, Object value)
  3. setField(Class cls, Object obj, String fieldName, Object value)
  4. setField(Class type, String name, Object instance, Object value)
  5. setField(Class klazz, Object recipient, String fieldName, Object newValue)
  6. setField(Class c, Object inst, String name, Object value)
  7. setField(Class cl, String name, Object obj, Object value)
  8. setField(Class clazz, Object instance, String field, Object value)
  9. setField(Class clazz, Object obj, String fieldName, Object value)