01: /*
02: * Copyright 2004,2004 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.apache.bsf.engines.javaclass;
18:
19: import java.lang.reflect.InvocationTargetException;
20: import java.lang.reflect.Method;
21:
22: import org.apache.bsf.BSFException;
23: import org.apache.bsf.util.BSFEngineImpl;
24: import org.apache.bsf.util.MethodUtils;
25:
26: /**
27: * This is the interface to scripts consisting of Java objects from the
28: * Bean Scripting Framework.
29: *
30: * @author Sanjiva Weerawarana
31: */
32: public class JavaClassEngine extends BSFEngineImpl {
33: /**
34: * call the named method of the given object. If object is an instance
35: * of Class, then the call is a static call on that object. If not, its
36: * an instance method call or a static call (as per Java) on the given
37: * object.
38: */
39: public Object call(Object object, String method, Object[] args)
40: throws BSFException {
41: // determine arg types
42: Class[] argTypes = null;
43: if (args != null) {
44: argTypes = new Class[args.length];
45: for (int i = 0; i < args.length; i++) {
46: argTypes[i] = (args[i] != null) ? args[i].getClass()
47: : null;
48: }
49: }
50:
51: // now find method with the right signature, call it and return result
52: try {
53: Method m = MethodUtils.getMethod(object, method, argTypes);
54: return m.invoke(object, args);
55: } catch (Exception e) {
56: // something went wrong while invoking method
57: Throwable t = (e instanceof InvocationTargetException) ? ((InvocationTargetException) e)
58: .getTargetException()
59: : null;
60: throw new BSFException(BSFException.REASON_OTHER_ERROR,
61: "method invocation failed: "
62: + e
63: + ((t == null) ? ""
64: : (" target exception: " + t)), t);
65: }
66: }
67:
68: /**
69: * This is used by an application to evaluate an object containing
70: * some expression - clearly not possible for compiled code ..
71: */
72: public Object eval(String source, int lineNo, int columnNo,
73: Object oscript) throws BSFException {
74: throw new BSFException(BSFException.REASON_UNSUPPORTED_FEATURE,
75: "Java bytecode engine can't evaluate expressions");
76: }
77: }
|