001    package org.codehaus.groovy.runtime;
002    
003    import java.lang.reflect.Method;
004    import java.security.AccessController;
005    import java.security.PrivilegedAction;
006    
007    import groovy.lang.Closure;
008    
009    
010    /**
011     * Represents a method on an object using a closure which can be invoked
012     * at any time
013     * 
014     * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
015     * @version $Revision: 1.11 $
016     */
017    public class MethodClosure extends Closure {
018    
019        private String method;
020        
021        public MethodClosure(Object owner, String method) {
022            super(owner);
023            this.method = method;
024    
025            final Class clazz = owner.getClass();
026            maximumNumberOfParameters = 0;
027    
028            Method[] methods = (Method[]) AccessController.doPrivileged(new  PrivilegedAction() {
029                public Object run() {
030                    return clazz.getMethods();
031                }
032            });
033            for (int j = 0; j < methods.length; j++) {
034                if (method.equals(methods[j].getName()) && methods[j].getParameterTypes().length > maximumNumberOfParameters) {
035                    maximumNumberOfParameters = methods[j].getParameterTypes().length;
036                }
037            }        
038            methods = (Method[]) AccessController.doPrivileged(new  PrivilegedAction() {
039                public Object run() {
040                    return clazz.getDeclaredMethods();
041                }
042            });
043            for (int j = 0; j < methods.length; j++) {
044                if (method.equals(methods[j].getName()) && methods[j].getParameterTypes().length > maximumNumberOfParameters) {
045                    maximumNumberOfParameters = methods[j].getParameterTypes().length;
046                }
047            }
048    
049        }
050        
051        public String getMethod() {
052            return method;
053        }
054    
055        protected Object doCall(Object arguments) {
056            return InvokerHelper.invokeMethod(getDelegate(), method, arguments);
057        }
058        
059        public Object getProperty(String property) {
060            if ("method".equals(property)) {
061                return getMethod();
062            } else  return super.getProperty(property);        
063        }
064    }