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