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: 4611 $
    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()==Class.class?(Class) owner:owner.getClass();
    26
    27          maximumNumberOfParameters = 0;
    28
    29          Method[] methods = (Method[]) AccessController.doPrivileged(new  PrivilegedAction() {
    30              public Object run() {
    31                  return clazz.getMethods();
    32              }
    33          });
    34          for (int j = 0; j < methods.length; j++) {
    35              if (method.equals(methods[j].getName()) && methods[j].getParameterTypes().length > maximumNumberOfParameters) {
    36                  maximumNumberOfParameters = methods[j].getParameterTypes().length;
    37              }
    38          }
    39          methods = (Method[]) AccessController.doPrivileged(new  PrivilegedAction() {
    40              public Object run() {
    41                  return clazz.getDeclaredMethods();
    42              }
    43          });
    44          for (int j = 0; j < methods.length; j++) {
    45              if (method.equals(methods[j].getName()) && methods[j].getParameterTypes().length > maximumNumberOfParameters) {
    46                  maximumNumberOfParameters = methods[j].getParameterTypes().length;
    47              }
    48          }
    49
    50      }
    51
    52      public String getMethod() {
    53          return method;
    54      }
    55
    56      protected Object doCall(Object arguments) {
    57          return InvokerHelper.invokeMethod(getDelegate(), method, arguments);
    58      }
    59
    60      public Object getProperty(String property) {
    61          if ("method".equals(property)) {
    62              return getMethod();
    63          } else  return super.getProperty(property);
    64      }
    65  }