Here you can find the source of setField(Class super T> clazz, String fieldName, T instance, Object value)
Parameter | Description |
---|---|
clazz | the class on which the field is declared |
fieldName | the field name |
instance | the instance to set the field on (null for static fields) |
value | the value to set |
T | the instance's type |
public static <T> void setField(Class<? super T> clazz, String fieldName, T instance, Object value)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Field; public class Main { /**// ww w . j a v a 2 s.com * Sets the field of the given class. * * @param clazz the class on which the field is declared * @param fieldName the field name * @param instance the instance to set the field on (null for static fields) * @param value the value to set * @param <T> the instance's type */ public static <T> void setField(Class<? super T> clazz, String fieldName, T instance, Object value) { try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); field.set(instance, value); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException("Could not set field '" + fieldName + "' on " + instance, e); } } }