Here you can find the source of setField(Object obj, String name, Object value)
public static void setField(Object obj, String name, Object value)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Main { public static void setField(Object obj, String name, Object value) { try {//from ww w . ja v a2s .co m getFieldAndEnsureItsAccessible(obj, name).set(obj, value); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private static Field getFieldAndEnsureItsAccessible(Object obj, String name) { Class klass = obj instanceof Class ? (Class) obj : obj.getClass(); Field field = null; do { try { field = klass.getDeclaredField(name); } catch (NoSuchFieldException e) { } klass = klass.getSuperclass(); if (klass == null) { throw new NoSuchFieldError(); } } while (field == null); if (!field.isAccessible()) { field.setAccessible(true); } try { Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } return field; } }