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 DefaultMappedPropertySetter<B>
29 implements BeanPropertySetter<B>
30 {
31
32 private final B bean;
33
34 private final String propertyName;
35
36 private final Method mappedSetterMethod;
37
38 private final String key;
39
40 public DefaultMappedPropertySetter( B bean, String propertyName, Method mappedSetterMethod, String key )
41 {
42 this.bean = bean;
43 this.propertyName = propertyName;
44 this.mappedSetterMethod = mappedSetterMethod;
45 this.key = key;
46 }
47
48 public <V> BeanAccessor<B> with( V value )
49 {
50 Class<?> paramType = mappedSetterMethod.getParameterTypes()[1];
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!", value.getClass().getName(),
60 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 mappedSetterMethod.invoke( bean, key, value );
73 }
74 catch ( IllegalAccessException e )
75 {
76 throw new PropertySetterNotAccessibleException( propertyName, mappedSetterMethod.getName(),
77 bean.getClass(), e );
78 }
79 catch ( InvocationTargetException e )
80 {
81 throw new PropertySetterInvocationException( propertyName, mappedSetterMethod.getName(), bean.getClass(), e );
82 }
83 }
84
85 }