Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.expressionevaluator / org.gvsig.expressionevaluator.lib / org.gvsig.expressionevaluator.lib.impl / src / main / java / org / gvsig / expressionevaluator / impl / function / obj / InvokeMethodFunction.java @ 44098

History | View | Annotate | Download (2.32 KB)

1
package org.gvsig.expressionevaluator.impl.function.obj;
2

    
3
import java.lang.reflect.Method;
4
import org.apache.commons.lang3.Range;
5
import org.gvsig.expressionevaluator.Function;
6
import org.gvsig.expressionevaluator.Interpreter;
7
import org.gvsig.expressionevaluator.spi.AbstractFunction;
8

    
9
public class InvokeMethodFunction extends AbstractFunction {
10

    
11
    private final Object obj;
12
    private final String methodname;
13

    
14
    public InvokeMethodFunction(Object obj, String methodName) {
15
        super(
16
            Function.GROUP_OTHER, 
17
            "CALLM", 
18
            Range.between(0, Integer.MAX_VALUE),
19
            null,
20
            null,
21
            null,
22
            "Object",
23
            false
24
        );
25
        this.obj = obj;
26
        this.methodname = methodName;
27
    }
28
    
29
    public InvokeMethodFunction() {
30
        super(
31
            Function.GROUP_OTHER, "invokeMethod", Range.between(2, Integer.MAX_VALUE)
32
        );
33
        this.obj = null;
34
        this.methodname = null;
35
    }
36
    
37
    @Override
38
    public Object call(Interpreter interpreter, Object[] args) throws Exception {
39
        Object theObj = this.obj;
40
        String theMethodName = this.methodname;
41
        int firstArg = 0;
42
        if( theObj==null && theMethodName==null ) {
43
            theObj = getObject(args, 0);
44
            theMethodName = getStr(args, 1);
45
            firstArg = 2;
46
        }
47
        if( theMethodName == null ) {
48
            throw new NullPointerException("A method name was expected to invoke and a null was received");
49
        }
50
        if( theObj==null ) {
51
            throw new NullPointerException("An object pointer was expected to invoke method "+theMethodName+" and a null was received");
52
        }
53
        Class[] parameterTypes = new Class[args.length-firstArg];
54
        Object[] parameters = new Object[args.length-firstArg];
55
        for (int i = 0; i < parameters.length; i++) {
56
            Object parameter = args[i+firstArg];
57
            parameters[i] = parameter;
58
            if( parameter==null ) {
59
                parameterTypes[i] = null;
60
            } else {
61
                parameterTypes[i] = parameter.getClass();
62
            }
63
        }
64
        Class<?> theClass = theObj.getClass();
65
        Method method = theClass.getMethod(theMethodName, parameterTypes);
66
        Object value = method.invoke(theObj, parameters);
67
        return value;
68
    }
69
    
70
}