Here you can find the source of setField(Class
Parameter | Description |
---|---|
clazz | The class of the object |
instance | The instance to modify (pass null for static fields) |
fieldName | The field name |
value | The value to set the field to |
public static <T> void setField(Class<T> clazz, T instance, String fieldName, Object value)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Field; import static java.lang.String.format; public class Main { /**/*from w ww . j a va 2 s . c o m*/ * Set the field of a given object to a new value with reflection. * * @param clazz The class of the object * @param instance The instance to modify (pass null for static fields) * @param fieldName The field name * @param value The value to set the field to */ public static <T> void setField(Class<T> clazz, T instance, String fieldName, Object value) { try { Field field = getField(clazz, instance, fieldName); field.set(instance, value); } catch (IllegalAccessException e) { throw new RuntimeException(format("Could not set value to field '%s' for instance '%s' of class '%s'", fieldName, instance, clazz.getName()), e); } } private static <T> Field getField(Class<T> clazz, T instance, String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { throw new RuntimeException(format("Could not get field '%s' for instance '%s' of class '%s'", fieldName, instance, clazz.getName()), e); } } }