Here you can find the source of setFieldValue(Object obj, String field, Object value)
public static void setFieldValue(Object obj, String field, Object value)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class Main { static Map<Class<?>, Map<String, Field>> cache = new HashMap<Class<?>, Map<String, Field>>(); public static void setFieldValue(Object obj, String field, Object value) { setFieldValue(obj, getField(obj.getClass(), field), value); }// ww w .j ava2s . c o m public static void setFieldValue(Object obj, Field field, Object value) { try { boolean accessible = field.isAccessible(); field.setAccessible(true); field.set(obj, value); field.setAccessible(accessible); } catch (IllegalArgumentException e) { throw new RuntimeException("IllegalArgumentException", e); } catch (IllegalAccessException e) { throw new RuntimeException("IllegalAccessExceptione", e); } } /** * Gets field from class cls, either declared in cls or in one * of its superclasses * * @param cls - declaring class of the field * @param fieldName - name of the field * @return requested field */ public static Field getField(Class<?> cls, String fieldName) { Field f = null; Map<String, Field> inner = cache.get(cls); if (inner != null) { f = inner.get(fieldName); if (f != null) return f; } else { inner = new HashMap<String, Field>(); cache.put(cls, inner); } try { while (cls != null) { try { f = cls.getDeclaredField(fieldName); f.setAccessible(true); } catch (NoSuchFieldException e) { f = null; } if (f != null) break; cls = cls.getSuperclass(); } } catch (SecurityException e) { throw new RuntimeException("SecurityException", e); } if (f != null) { inner.put(fieldName, f); } return f; } }