Here you can find the source of setField(Object owner, String name, Object newValue, Class> definedIn)
public static void setField(Object owner, String name, Object newValue, Class<?> definedIn) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException
//package com.java2s; /******************************************************************************* * Copyright (c) 2013 Red Hat, Inc.// w w w . ja v a 2 s. co m * Distributed under license by Red Hat, Inc. All rights reserved. * This program is 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 * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ import java.lang.reflect.Field; public class Main { public static void setField(Object owner, String name, Object newValue, Class<?> definedIn) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = getFieldDescriptor(owner, name, definedIn); field.set(owner, newValue); } public static Field getFieldDescriptor(Object instance, String fieldName) throws NoSuchFieldException { Class<? extends Object> aClass = instance.getClass(); while (true) { try { return getFieldDescriptor(instance, fieldName, aClass); } catch (NoSuchFieldException e) { if (aClass != Object.class) { Class<?> superclass = aClass.getSuperclass(); if (superclass != null && superclass != Object.class && superclass != aClass) { aClass = superclass; continue; } } throw e; } } } public static Field getFieldDescriptor(Object instance, String fieldName, Class<? extends Object> aClass) throws NoSuchFieldException { notNull(instance, "instance"); Field field = aClass.getDeclaredField(fieldName); field.setAccessible(true); return field; } public static <T> T notNull(T value, String message) { if (value == null) { throw new IllegalArgumentException(message); } return value; } public static Field getDeclaredField(Class<?> aClass, String name) throws NoSuchFieldException { try { return aClass.getDeclaredField(name); } catch (NoSuchFieldException e) { Class<?> superclass = aClass.getSuperclass(); if (aClass == Object.class || superclass == null) { throw e; } else { return getDeclaredField(superclass, name); } } } }