Here you can find the source of setFieldViaReflection(String fieldName, V value, T classInstance)
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 |
Parameter | Description |
---|---|
Exception | if there was a problem setting the field value |
public static <V, T> void setFieldViaReflection(String fieldName, V value, T classInstance) throws Exception
//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); } }