Here you can find the source of setFieldValue(Object target, Class extends Object> targetClass, String fieldName, Object value)
private static void setFieldValue(Object target, Class<? extends Object> targetClass, String fieldName, Object value) throws IllegalAccessException
//package com.java2s; /*/*w w w . jav a 2 s . c om*/ * @(#)ReflectionUtils.java 7 Nov 2008 * * Copyright ? 2009 Andrew Phillips. * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ import java.lang.reflect.Field; public class Main { private static void setFieldValue(Object target, Class<? extends Object> targetClass, String fieldName, Object value) throws IllegalAccessException { try { Field field = getAccessibleField((target != null) ? target.getClass() : targetClass, fieldName); field.set(target, value); } catch (Exception exception) { boolean instanceFieldRequested = (target != null); throw new IllegalAccessException(String.format("Unable to set field '%s' on %s '%s' due to %s: %s", fieldName, instanceFieldRequested ? "object" : "class", instanceFieldRequested ? target : targetClass.getName(), exception.getClass().getSimpleName(), exception.getMessage())); } } private static Field getAccessibleField(Class<? extends Object> targetClass, String fieldName) throws SecurityException, NoSuchFieldException { Class<?> currentClass = targetClass; Field field = null; // the loop will be exited if the current class is Object.class and nothing is found do { try { field = currentClass.getDeclaredField(fieldName); } catch (NoSuchFieldException exception) { // try the superclass currentClass = currentClass.getSuperclass(); } } while ((field == null) && (currentClass != null)); if (field == null) { throw new NoSuchFieldException(fieldName); } if (!field.isAccessible()) { field.setAccessible(true); } return field; } }