Java Reflection Field Set setFieldViaReflection(String fieldName, V value, T classInstance)

Here you can find the source of setFieldViaReflection(String fieldName, V value, T classInstance)

Description

Sets the value of a field for a given instance using Reflection API.

License

LGPL

Parameter

Parameter Description
fieldName the name of the target field
value the value to set the field to
classInstance the instance of the class containing the field to be set
V the value data type
T the class type of the instance

Exception

Parameter Description
Exception if there was a problem setting the field value

Declaration

public static <V, T> void setFieldViaReflection(String fieldName, V value, T classInstance) throws Exception 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.lang.reflect.Field;

public class Main {
    /**//  w  w w .jav  a  2s .c  om
     * Sets the value of a field for a given instance using Reflection API.
     * @param fieldName the name of the target field
     * @param value the value to set the field to
     * @param classInstance the instance of the class containing the field to be set
     * @param <V> the value data type
     * @param <T> the class type of the instance
     * @throws Exception if there was a problem setting the field value
     */
    public static <V, T> void setFieldViaReflection(String fieldName, V value, T classInstance) throws Exception {
        Field targetField = classInstance.getClass().getDeclaredField(fieldName);
        targetField.setAccessible(true);
        targetField.set(classInstance, value);
    }
}

Related

  1. setFields(Field field, Object value, Object config)
  2. setFields(final Map fields, final Object target)
  3. setFieldStatic(final Object pBean, final String fieldname, final Object pInject)
  4. setFieldVal(Object object, String name, Object val)
  5. setFieldValeByType(Field field, Object obj, String value)
  6. setFieldVisible( Class classToModify, String fieldName)
  7. setFieldWithReflection(Object object, String fieldName, Object fieldValue)