Here you can find the source of setField(String fieldName, Object instance, Class instanceClass, Object value)
@SuppressWarnings("unchecked") public static void setField(String fieldName, Object instance, Class instanceClass, Object value)
//package com.java2s; /******************************************************************************* * Copyright (c) 2005-2012 eBay Inc.//from w w w . j ava 2s .co m * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ import java.lang.reflect.Field; public class Main { @SuppressWarnings("unchecked") public static void setField(String fieldName, Object instance, Class instanceClass, Object value) { if (instanceClass == null) { throw new RuntimeException("NoSuchField: " + fieldName); } try { Field field = instanceClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(instance, value); } catch (NoSuchFieldException e) { setField(fieldName, instance, instanceClass.getSuperclass(), value); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static void setField(String fieldName, Object instance, Object value) { setField(fieldName, instance, instance.getClass(), value); } }