View Javadoc

1   package org.apache.velocity.runtime.parser.node;
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 java.util.Map;
23  
24  import org.apache.velocity.runtime.log.Log;
25  
26  /**
27   * GetExecutor that is smart about Maps. If it detects one, it does not
28   * use Reflection but a cast to access the getter. 
29   *
30   * @author <a href="mailto:henning@apache.org">Henning P. Schmiedehausen</a>
31   * @version $Id: MapGetExecutor.java 463298 2006-10-12 16:10:32Z henning $
32   */
33  public class MapGetExecutor
34          extends AbstractExecutor 
35  {
36      private final String property;
37  
38      public MapGetExecutor(final Log log, final Class clazz, final String property)
39      {
40          this.log = log;
41          this.property = property;
42          discover(clazz);
43      }
44  
45      protected void discover (final Class clazz)
46      {
47          Class [] interfaces = clazz.getInterfaces();
48          for (int i = 0 ; i < interfaces.length; i++)
49          {
50              if (interfaces[i].equals(Map.class))
51              {
52                  try
53                  {
54                      if (property != null)
55                      {
56                          setMethod(Map.class.getMethod("get", new Class [] { Object.class }));
57                      }
58                  }
59                  /**
60                   * pass through application level runtime exceptions
61                   */
62                  catch( RuntimeException e )
63                  {
64                      throw e;
65                  }
66                  catch(Exception e)
67                  {
68                      log.error("While looking for get('" + property + "') method:", e);
69                  }
70                  break;
71              }
72          }
73      }
74  
75      public Object execute(final Object o)
76      {
77          return ((Map) o).get(property);
78      } 
79  }