Here you can find the source of setFieldValue(Object obj, String fieldName, Object value)
public static void setFieldValue(Object obj, String fieldName, Object value) throws NoSuchFieldException
//package com.java2s; /*L//from w ww .j a va2 s .c om * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cabio/LICENSE.txt for details. */ import java.lang.reflect.Field; public class Main { /** * Set the given field on the specified object. If the field is * private, this subverts the security manager to set the value anyway. */ public static void setFieldValue(Object obj, String fieldName, Object value) throws NoSuchFieldException { try { getField(obj, fieldName).set(obj, value); } catch (IllegalAccessException e) { // shouldnt happen since getField sets the field accessible e.printStackTrace(); throw new RuntimeException("Field cannot be accessed", e); } } /** * Set the given attribute on the specified object, * using the public setter method. */ public static void set(Object obj, String attributeName, Object value) throws Exception { Class[] argTypes = { value.getClass() }; Object[] argValues = { value }; String methodName = getAccessor("set", attributeName); obj.getClass().getMethod(methodName, argTypes).invoke(obj, argValues); } private static Field getField(Object obj, String fieldName) throws NoSuchFieldException { final Field fields[] = obj.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (fieldName.equals(field.getName())) { field.setAccessible(true); return field; } } throw new NoSuchFieldException(fieldName); } private static String getAccessor(String prefix, String attributeName) throws NoSuchMethodException { String firstChar = attributeName.substring(0, 1).toUpperCase(); return prefix + firstChar + attributeName.substring(1); } }