Here you can find the source of setField(Field field, T newValue, Object instance)
private static <T> Object setField(Field field, T newValue, Object instance) throws IllegalArgumentException, IllegalAccessException
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Field; public class Main { private static <T> Object setField(Field field, T newValue, Object instance) throws IllegalArgumentException, IllegalAccessException { Object old = null;//from w w w.j ava 2 s . c om final boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(!accessible); } old = retrieveField(field, instance); field.set(instance, newValue); field.setAccessible(accessible); return old; } private static Object retrieveField(Field field, Object obj) throws IllegalArgumentException, IllegalAccessException { Object item = null; final boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(!accessible); } item = field.get(obj); if (!accessible) { field.setAccessible(accessible); } return item; } }