Here you can find the source of setField(Object target, String fieldName, Class
public static <T> void setField(Object target, String fieldName, Class<T> fieldType, T value)
//package com.java2s; //License from project: Apache License import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class Main { public static <T> void setField(Object target, String fieldName, Class<T> fieldType, T value) { Field field = findField(target.getClass(), fieldName, fieldType); if (field == null) { throw new RuntimeException("unknown given field '" + fieldName + "'"); }/* w w w .j av a 2 s .c o m*/ makeAccessible(field); try { field.set(target, value); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static Field findField(Class<?> clazz, String name, Class<?> type) { Class<?> searchType = clazz; while (!Object.class.equals(searchType) && searchType != null) { Field[] fields = searchType.getDeclaredFields(); for (Field field : fields) { if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) { return field; } } searchType = searchType.getSuperclass(); } return null; } private static void makeAccessible(Field field) { if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) { field.setAccessible(true); } } private static void makeAccessible(Method method) { if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) { method.setAccessible(true); } } }