Here you can find the source of setField(final Object obj, final String variableName, final Object variableValue)
Parameter | Description |
---|---|
obj | - object to set the variable on |
variableName | - name onf the variable to set |
variableValue | - value of the variable to be set |
public static void setField(final Object obj, final String variableName, final Object variableValue)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Field; public class Main { /**/*from w w w . j a va 2 s .c o m*/ * Sets variable by reflection down to 3 levels of abstracts classes. * * @param obj - object to set the variable on * @param variableName - name onf the variable to set * @param variableValue - value of the variable to be set */ public static void setField(final Object obj, final String variableName, final Object variableValue) { Field declaredField = null; Class<?> clazz = obj.getClass(); for (int i = 0; i <= 3; i++) { try { declaredField = clazz.getDeclaredField(variableName); break; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } declaredField.setAccessible(true); try { declaredField.set(obj, variableValue); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } } }