1 package org.apache.commons.beanutils2;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import static org.apache.commons.beanutils2.Assertions.checkArgument;
23 import static org.apache.commons.beanutils2.TypeUtils.isAssignmentCompatible;
24
25 import java.lang.reflect.InvocationTargetException;
26 import java.lang.reflect.Method;
27
28 final class DefaultBeanPropertySetter<B>
29 implements BeanPropertySetter<B>
30 {
31
32 private final B bean;
33
34 private final Method setterMethod;
35
36 private final String propertyName;
37
38 public DefaultBeanPropertySetter( B bean, Method setterMethod, String propertyName )
39 {
40 this.bean = bean;
41 this.setterMethod = setterMethod;
42 this.propertyName = propertyName;
43 }
44
45
46
47
48 public <V> BeanAccessor<B> with( V value )
49 {
50 Class<?> paramType = setterMethod.getParameterTypes()[0];
51
52 if ( value == null )
53 {
54 checkArgument( !paramType.isPrimitive(), "Null can not be assigned to a primitive property!" );
55 }
56 else
57 {
58 checkArgument( isAssignmentCompatible( paramType, value.getClass() ),
59 "Value of type %s is not compatible to parameter type %s!",
60 value.getClass().getName(), paramType.getName() );
61 }
62
63 invokeSetter( value );
64
65 return new DefaultBeanAccessor<B>( bean );
66 }
67
68 private <V> void invokeSetter( V value )
69 {
70 try
71 {
72 setterMethod.invoke( bean, value );
73 }
74 catch ( IllegalAccessException e )
75 {
76 throw new PropertySetterNotAccessibleException( propertyName, setterMethod.getName(), bean.getClass(), e );
77 }
78 catch ( InvocationTargetException e )
79 {
80 throw new PropertySetterInvocationException( propertyName, setterMethod.getName(), bean.getClass(), e );
81 }
82 }
83
84 }