1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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. import java.lang.reflect.Constructor;
  18. import java.lang.reflect.InvocationTargetException;
  19. import org.apache.commons.jxpath.ExpressionContext;
  20. import org.apache.commons.jxpath.Function;
  21. import org.apache.commons.jxpath.JXPathException;
  22. import org.apache.commons.jxpath.util.TypeUtils;
  23. /**
  24. * An extension function that creates an instance using a constructor.
  25. *
  26. * @author Dmitri Plotnikov
  27. * @version $Revision: 1.11 $ $Date: 2004/02/29 14:17:44 $
  28. */
  29. public class ConstructorFunction implements Function {
  30. private Constructor constructor;
  31. private static final Object EMPTY_ARRAY[] = new Object[0];
  32. public ConstructorFunction(Constructor constructor) {
  33. this.constructor = constructor;
  34. }
  35. /**
  36. * Converts parameters to suitable types and invokes the constructor.
  37. */
  38. public Object invoke(ExpressionContext context, Object[] parameters) {
  39. try {
  40. Object[] args;
  41. if (parameters == null) {
  42. parameters = EMPTY_ARRAY;
  43. }
  44. int pi = 0;
  45. Class types[] = constructor.getParameterTypes();
  46. if (types.length > 0
  47. && ExpressionContext.class.isAssignableFrom(types[0])) {
  48. pi = 1;
  49. }
  50. args = new Object[parameters.length + pi];
  51. if (pi == 1) {
  52. args[0] = context;
  53. }
  54. for (int i = 0; i < parameters.length; i++) {
  55. args[i + pi] = TypeUtils.convert(parameters[i], types[i + pi]);
  56. }
  57. return constructor.newInstance(args);
  58. }
  59. catch (Throwable ex) {
  60. if (ex instanceof InvocationTargetException) {
  61. ex = ((InvocationTargetException) ex).getTargetException();
  62. }
  63. throw new JXPathException(
  64. "Cannot invoke constructor " + constructor,
  65. ex);
  66. }
  67. }
  68. }