01: /*
02: * Copyright 1999-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: package org.apache.commons.jxpath.functions;
17:
18: import java.lang.reflect.Constructor;
19: import java.lang.reflect.InvocationTargetException;
20:
21: import org.apache.commons.jxpath.ExpressionContext;
22: import org.apache.commons.jxpath.Function;
23: import org.apache.commons.jxpath.JXPathException;
24: import org.apache.commons.jxpath.util.TypeUtils;
25:
26: /**
27: * An extension function that creates an instance using a constructor.
28: *
29: * @author Dmitri Plotnikov
30: * @version $Revision: 1.11 $ $Date: 2004/02/29 14:17:44 $
31: */
32: public class ConstructorFunction implements Function {
33:
34: private Constructor constructor;
35: private static final Object EMPTY_ARRAY[] = new Object[0];
36:
37: public ConstructorFunction(Constructor constructor) {
38: this .constructor = constructor;
39: }
40:
41: /**
42: * Converts parameters to suitable types and invokes the constructor.
43: */
44: public Object invoke(ExpressionContext context, Object[] parameters) {
45: try {
46: Object[] args;
47: if (parameters == null) {
48: parameters = EMPTY_ARRAY;
49: }
50: int pi = 0;
51: Class types[] = constructor.getParameterTypes();
52: if (types.length > 0
53: && ExpressionContext.class
54: .isAssignableFrom(types[0])) {
55: pi = 1;
56: }
57: args = new Object[parameters.length + pi];
58: if (pi == 1) {
59: args[0] = context;
60: }
61: for (int i = 0; i < parameters.length; i++) {
62: args[i + pi] = TypeUtils.convert(parameters[i], types[i
63: + pi]);
64: }
65: return constructor.newInstance(args);
66: } catch (Throwable ex) {
67: if (ex instanceof InvocationTargetException) {
68: ex = ((InvocationTargetException) ex)
69: .getTargetException();
70: }
71: throw new JXPathException("Cannot invoke constructor "
72: + constructor, ex);
73: }
74: }
75: }
|