Here you can find the source of setField(Object obj, String fieldName, Object val)
public static void setField(Object obj, String fieldName, Object val) throws Exception
//package com.java2s; /*/*w ww .j av a 2 s .com*/ * Copyright 2012 Evgeny Dolganov (evgenij.dolganov@gmail.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Field; public class Main { public static void setField(Object obj, String fieldName, Object val) throws Exception { getFieldDef(obj.getClass(), fieldName).set(obj, val); } public static Field getFieldDef(Class<?> clazz, String fieldName) throws Exception { return getFieldDef(clazz, fieldName, true); } public static Field getFieldDef(Class<?> clazz, String fieldName, boolean accessible) throws Exception { Field field = null; while (clazz != null) { try { field = clazz.getDeclaredField(fieldName); clazz = null; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } if (field == null) { throw new NoSuchFieldException(fieldName); } if (accessible) field.setAccessible(true); return field; } }