1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.isAssignableFrom(types[0])) {
54 pi = 1;
55 }
56 args = new Object[parameters.length + pi];
57 if (pi == 1) {
58 args[0] = context;
59 }
60 for (int i = 0; i < parameters.length; i++) {
61 args[i + pi] = TypeUtils.convert(parameters[i], types[i + pi]);
62 }
63 return constructor.newInstance(args);
64 }
65 catch (Throwable ex) {
66 if (ex instanceof InvocationTargetException) {
67 ex = ((InvocationTargetException) ex).getTargetException();
68 }
69 throw new JXPathException(
70 "Cannot invoke constructor " + constructor,
71 ex);
72 }
73 }
74 }