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

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

Description

set Field

License

Open Source License

Declaration

public static void setField(Class clazz, Object src, String fieldName,
            Object value) throws NoSuchFieldException,
            IllegalAccessException 

Method Source Code

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

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Main {
    public static void setField(Object src, String fieldName, Object value)
            throws NoSuchFieldException, IllegalAccessException {
        setField(src.getClass(), src, fieldName, value);
    }/*from   w  w w  .j a  v a 2s  .  c  om*/

    public static void setField(Class clazz, Object src, String fieldName,
            Object value) throws NoSuchFieldException,
            IllegalAccessException {
        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);
    }
}

Related

  1. setField(Class clazz, Object instance, 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)