Here you can find the source of setField(final O object, final String fieldName, final V value)
Parameter | Description |
---|---|
O | the type of object to update. |
V | the type of value to set. |
object | the object. |
fieldName | the name of the field to set. |
value | the value to set. |
Parameter | Description |
---|---|
SecurityException | if there is a problem getting the field of the object. |
NoSuchFieldException | if the field does not exist. |
IllegalAccessException | if the field cannot be accessed. |
IllegalArgumentException | if the object is not a valid field. |
public final static <O, V> V setField(final O object, final String fieldName, final V value) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
//package com.java2s; import java.lang.reflect.Field; public class Main { /**/*from w w w . jav a 2 s. co m*/ * Sets a field on an object, even if the field would not normally be accessible (such as a private field). * <p> * * @author Ian Andrew Brown * @param <O> * the type of object to update. * @param <V> * the type of value to set. * @param object * the object. * @param fieldName * the name of the field to set. * @param value * the value to set. * @return the old value. * @throws SecurityException * if there is a problem getting the field of the object. * @throws NoSuchFieldException * if the field does not exist. * @throws IllegalAccessException * if the field cannot be accessed. * @throws IllegalArgumentException * if the object is not a valid field. * @since V2.2.0 Oct 4, 2014 * @version V2.2.0 Oct 4, 2014 */ public final static <O, V> V setField(final O object, final String fieldName, final V value) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Field objectField = null; Class<?> workingClass = object.getClass(); while (objectField == null) { try { objectField = workingClass.getDeclaredField(fieldName); } catch (final NoSuchFieldException e) { if (workingClass == Object.class) { throw e; } workingClass = workingClass.getSuperclass(); } } objectField.setAccessible(true); @SuppressWarnings("unchecked") final V oldValue = (V) objectField.get(object); objectField.set(object, value); return oldValue; } }