Here you can find the source of setFieldValue(Class
@SuppressWarnings("unchecked") public static <T> T setFieldValue(Class<T> expectedType, Object target, String fieldName, T value)
//package com.java2s; /******************************************************************************* * Copyright (c) 2008 flowr.org - all rights reserved. This program and the accompanying materials are made available * under the terms of the Eclipse Public License (EPL) v1.0. The EPL is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: flowr.org - initial API and implementation ******************************************************************************/ import java.lang.reflect.Field; public class Main { @SuppressWarnings("unchecked") public static <T> T setFieldValue(Class<T> expectedType, Object target, String fieldName, T value) { try {//ww w. ja v a 2 s.c o m Class<? extends Object> targetClass = target.getClass(); while (targetClass != null) { Field field = locateField(expectedType, targetClass, fieldName); if (field != null) { T oldValue = (T) field.get(target); field.set(target, value); return oldValue; } else { targetClass = targetClass.getSuperclass(); } } } catch (Exception e) { } return null; } private static Field locateField(Class<?> expectedType, Class<?> targetClass, String fieldName) { try { Field field = targetClass.getDeclaredField(fieldName); if (field != null) { field.setAccessible(true); if (expectedType.isAssignableFrom(field.getType())) { return field; } } } catch (Exception e) { } return null; } }