Java Utililty Methods Reflection Field Set

List of utility methods to do Reflection Field Set

Description

The list of methods to do Reflection Field Set are organized into topic(s).

Method

voidsetField(Class clazz, Object instance, String fieldName, Object value)
set Field
try {
    Field field = clazz.getDeclaredField(fieldName);
    boolean accessible = field.isAccessible();
    field.setAccessible(true);
    field.set(instance, value);
    field.setAccessible(accessible);
} catch (NoSuchFieldException e) {
    throw new IllegalArgumentException(
...
voidsetField(Class clazz, Object src, String fieldName, Object value)
set Field
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(src, value);
voidsetField(Class clazz, String name, Object value)
Assigns a value to a field of a given class.
setField(clazz, null, name, value);
voidsetField(Class cls, Object obj, String fieldName, Object value)
set Field
Field field = cls.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, value);
voidsetField(Class type, String name, Object instance, Object value)
set Field
Field field = type.getDeclaredField(name);
field.setAccessible(true);
field.set(instance, value);
voidsetField(Class klazz, Object recipient, String fieldName, Object newValue)
set Field
Field[] fields = klazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
    if (fields[i].getName().equals(fieldName)) {
        fields[i].setAccessible(true);
        try {
            fields[i].set(recipient, newValue);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Couldn't set field.", e);
...
voidsetField(Class clazz, String fieldName, T instance, Object value)
Sets the field of the given class.
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);
voidsetField(Class c, Object inst, String name, Object value)
changes a field in a class by using reflection
if (c == null)
    c = inst.getClass();
try {
    Field field = null;
    while (field == null) {
        try {
            field = c.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
...
voidsetField(Class cl, String name, Object obj, Object value)
set Field
Field field = cl.getDeclaredField(name);
field.setAccessible(true);
field.set(obj, value);
voidsetField(Class clazz, Object instance, String field, Object value)
set Field
Field f = clazz.getDeclaredField(field);
f.setAccessible(true);
f.set(instance, value);