Java Reflection Field Value Set setFieldValue(Class clazz, Object target, String fieldName, Object value)

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

Description

Set class field value, returns success status

License

Open Source License

Parameter

Parameter Description
clazz Class to scan
target Instance
fieldName Name of field

Declaration

public static void setFieldValue(Class clazz, Object target, 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;

import java.util.*;

public class Main {
    /**/*from  w  ww.j  ava 2  s .co m*/
     * Set class field value, returns success status
     * @param clazz Class to scan
     * @param target Instance
     * @param fieldName Name of field
     */
    public static void setFieldValue(Class clazz, Object target, String fieldName, Object value)
            throws NoSuchFieldException, IllegalAccessException {
        HashMap<String, Object> result = new HashMap<>();
        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(target, value);
    }
}

Related

  1. setFieldValue(Class c, Object instance, String name, Object value)
  2. setFieldValue(Class clazz, Object instance, String fieldName, T value)
  3. setFieldValue(Class clazz, E instance, Object value, String... names)
  4. setFieldValue(Class clazz, Object entity, String fieldName, V value)
  5. setFieldValue(Class clazz, String fieldName, Object value)
  6. setFieldValue(Class clazz, String fieldName, Object value)