KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > util > functions > MethodFunction


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.util.functions;
11
12
13 import java.lang.reflect.*;
14
15 /**
16  * A function based on an abritrary method. Since the name of the parameters cannot be found by
17  * reflection, this is only of limited use. Normally you would probably better use BeanFunction. A
18  * method-function can come in handy on JSP's.
19  *
20  * @author Michiel Meeuwissen
21  * @version $Id: MethodFunction.java,v 1.4 2005/10/01 20:17:36 michiel Exp $
22  * @see org.mmbase.module.core.MMObjectBuilder#executeFunction
23  * @see org.mmbase.bridge.Node#getFunctionValue
24  * @see org.mmbase.util.functions.BeanFunction
25  * @since MMBase-1.7
26  */

27 public class MethodFunction extends AbstractFunction {
28
29     public static Function getFunction(Method method, String JavaDoc name) {
30         return new MethodFunction(method, name); // could be cached...
31
}
32
33     private Method method = null;
34     public MethodFunction(Method method, String JavaDoc name) {
35         super(name, null, null);
36         this.method = method;
37         if (! Modifier.isStatic(method.getModifiers())) {
38             throw new IllegalArgumentException JavaDoc("The method " + method + " is not static"); // otherwise NPE in getFunctionValue
39
}
40
41         Class JavaDoc[] parameters = method.getParameterTypes();
42         Parameter[] def = new Parameter[parameters.length];
43         for (int i = 0; i < parameters.length; i++) {
44             def[i] = new Parameter("parameter" + (i + 1), parameters[i]); // no way to find the name of the parameter
45
}
46
47         setParameterDefinition(def);
48
49         ReturnType returnType = new ReturnType(method.getReturnType(), "");
50         setReturnType(returnType);
51
52     }
53
54     public Object JavaDoc getFunctionValue(Parameters parameters) {
55         try {
56             return method.invoke(null, parameters.toArray());
57         } catch (Exception JavaDoc e) {
58             throw new RuntimeException JavaDoc(e);
59         }
60     }
61
62 }
63
Popular Tags