Here you can find the source of setField(final Object instance, final String fieldName, final T value)
public static <T> void setField(final Object instance, final String fieldName, final T value)
//package com.java2s; /*/* w w w .ja v a 2 s .c om*/ * Copyright 2013-2015 Eris IT AB * * 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 <T> void setField(final Object instance, final String fieldName, final T value) { Class<?> instanceClass = instance.getClass(); Field field = getDeclaredField(instanceClass, fieldName); while (field == null) { instanceClass = instanceClass.getSuperclass(); field = getDeclaredField(instanceClass, fieldName); } field.setAccessible(true); try { field.set(instance, value); } catch (final IllegalAccessException e) { throw new RuntimeException(e); } finally { field.setAccessible(false); } } private static Field getDeclaredField(final Class<?> instanceClass, final String fieldName) { if (instanceClass == null) { throw new RuntimeException(new NoSuchFieldException(fieldName)); } try { return instanceClass.getDeclaredField(fieldName); } catch (final NoSuchFieldException | SecurityException e) { return null; } } }