Here you can find the source of setFieldValue(Object bean, Field field, Object value)
Parameter | Description |
---|---|
bean | The bean object to be manipulated |
field | The field definition in the model object to be set |
value | The value to be stored in that field. |
Parameter | Description |
---|---|
IllegalArgumentException | if the method is an instance method and the specified object argument is not an instance of the classor interface declaring the underlying method (or of a subclass or implementor thereof); if the numberof actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; orif, after possible unwrapping, a parameter value cannot be converted to the corresponding formalparameter type by a method invocation conversion. |
IllegalAccessException | if this Method object is enforcing Java language access control and the underlying method isinaccessible. |
public static void setFieldValue(Object bean, Field field, Object value) throws IllegalArgumentException, IllegalAccessException
//package com.java2s; import java.lang.reflect.Field; public class Main { /**//from w w w . j a v a 2 s . c o m * This method is used to set the value of a field of a model object to the specified value. * * @param bean * The bean object to be manipulated * @param field * The field definition in the model object to be set * @param value * The value to be stored in that field. * @throws IllegalArgumentException * if the method is an instance method and the specified object argument is not an instance of the class * or interface declaring the underlying method (or of a subclass or implementor thereof); if the number * of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or * if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal * parameter type by a method invocation conversion. * @throws IllegalAccessException * if this Method object is enforcing Java language access control and the underlying method is * inaccessible. */ public static void setFieldValue(Object bean, Field field, Object value) throws IllegalArgumentException, IllegalAccessException { Class<?> targetType = field.getType(); Class<?> sourceType = value.getClass(); if (targetType.isAssignableFrom(sourceType)) { field.setAccessible(true); field.set(bean, value); } else { throw new IllegalArgumentException(String.format( "Attempt to set property %s of type %s from a " + "value of type %s, types are not assignable.", field.getName(), targetType.getName(), sourceType.getName())); } } }