View Javadoc

1   package org.codehaus.groovy.runtime;
2   
3   import java.lang.reflect.Method;
4   import java.security.AccessController;
5   import java.security.PrivilegedAction;
6   
7   import groovy.lang.Closure;
8   
9   
10  /***
11   * Represents a method on an object using a closure which can be invoked
12   * at any time
13   * 
14   * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
15   * @version $Revision: 1.11 $
16   */
17  public class MethodClosure extends Closure {
18  
19      private String method;
20      
21      public MethodClosure(Object owner, String method) {
22          super(owner);
23          this.method = method;
24  
25          final Class clazz = owner.getClass();
26          maximumNumberOfParameters = 0;
27  
28          Method[] methods = (Method[]) AccessController.doPrivileged(new  PrivilegedAction() {
29              public Object run() {
30                  return clazz.getMethods();
31              }
32          });
33          for (int j = 0; j < methods.length; j++) {
34              if (method.equals(methods[j].getName()) && methods[j].getParameterTypes().length > maximumNumberOfParameters) {
35                  maximumNumberOfParameters = methods[j].getParameterTypes().length;
36              }
37          }        
38          methods = (Method[]) AccessController.doPrivileged(new  PrivilegedAction() {
39              public Object run() {
40                  return clazz.getDeclaredMethods();
41              }
42          });
43          for (int j = 0; j < methods.length; j++) {
44              if (method.equals(methods[j].getName()) && methods[j].getParameterTypes().length > maximumNumberOfParameters) {
45                  maximumNumberOfParameters = methods[j].getParameterTypes().length;
46              }
47          }
48  
49      }
50      
51      public String getMethod() {
52          return method;
53      }
54  
55      protected Object doCall(Object arguments) {
56          return InvokerHelper.invokeMethod(getDelegate(), method, arguments);
57      }
58      
59      public Object getProperty(String property) {
60          if ("method".equals(property)) {
61              return getMethod();
62          } else  return super.getProperty(property);        
63      }
64  }