View Javadoc
1   package org.apache.commons.beanutils2;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import static org.apache.commons.beanutils2.Assertions.checkArgument;
23  
24  import java.lang.reflect.InvocationTargetException;
25  import java.lang.reflect.Method;
26  
27  final class DefaultIndexedPropertyGetterAccessor<B>
28      implements IndexedPropertyGetterAccessor<B>
29  {
30  
31      private final B bean;
32  
33      private final String propertyName;
34  
35      private final Method indexedReadMethod;
36  
37      public DefaultIndexedPropertyGetterAccessor( B bean, String propertyName, Method indexedReadMethod )
38      {
39          this.bean = bean;
40          this.propertyName = propertyName;
41          this.indexedReadMethod = indexedReadMethod;
42      }
43  
44      /**
45       * {@inheritDoc}
46       */
47      public BeanAccessor<?> at( int index )
48      {
49          checkArgument( index >= 0, "Indexed property '%s' in bean of type %s cannot be get from a negative index %s",
50                         propertyName, bean.getClass().getName(), index );
51          Object indexedValue = invokeGetter( index );
52          return new DefaultBeanAccessor<Object>( indexedValue );
53      }
54  
55      private Object invokeGetter( int index )
56      {
57          try
58          {
59              return indexedReadMethod.invoke( bean, index );
60          }
61          catch ( IllegalAccessException e )
62          {
63              throw new PropertyGetterNotAccessibleException( propertyName, indexedReadMethod.getName(), bean.getClass(), e );
64          }
65          catch ( InvocationTargetException e )
66          {
67              throw new PropertyGetterInvocationException( propertyName, indexedReadMethod.getName(), bean.getClass(), e );
68          }
69      }
70  
71  }