Here you can find the source of setFieldValue(Object objectInstance, String fieldName, Object valueToSet)
Parameter | Description |
---|---|
objectInstance | the object instance |
fieldName | the field name |
valueToSet | the value to set |
Parameter | Description |
---|---|
NoSuchFieldException | the no such field exception |
IllegalArgumentException | the illegal argument exception |
IllegalAccessException | the illegal access exception |
public static void setFieldValue(Object objectInstance, String fieldName, Object valueToSet) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException
//package com.java2s; import java.lang.reflect.Field; public class Main { /**//from ww w . ja va 2s.com * Sets the field value. * * @param objectInstance the object instance * @param fieldName the field name * @param valueToSet the value to set * @throws NoSuchFieldException the no such field exception * @throws IllegalArgumentException the illegal argument exception * @throws IllegalAccessException the illegal access exception */ public static void setFieldValue(Object objectInstance, String fieldName, Object valueToSet) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (null == objectInstance) return; Field fld = getFieldByName(objectInstance.getClass(), fieldName); if (fld == null) throw new NoSuchFieldException("Field not found: " + fieldName); if (!fld.isAccessible()) fld.setAccessible(true); fld.set(objectInstance, valueToSet); } /** * Gets the field by name. * @param cls the class to work with * @param name the name * @return the field by name */ public static Field getFieldByName(Class<?> cls, String name) { if (cls == null || cls.isPrimitive()) return null; Field field = null; try { field = cls.getDeclaredField(name); } catch (Exception e) { } return (field != null) ? field : getFieldByName(cls.getSuperclass(), name); } }