1. /*
  2. * Copyright 2001-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.collections.functors;
  17. import java.io.Serializable;
  18. import org.apache.commons.collections.Closure;
  19. import org.apache.commons.collections.Transformer;
  20. /**
  21. * Transformer implementation that calls a Closure using the input object
  22. * and then returns the input.
  23. *
  24. * @since Commons Collections 3.0
  25. * @version $Revision: 1.5 $ $Date: 2004/05/16 11:36:31 $
  26. *
  27. * @author Stephen Colebourne
  28. */
  29. public class ClosureTransformer implements Transformer, Serializable {
  30. /** Serial version UID */
  31. static final long serialVersionUID = 478466901448617286L;
  32. /** The closure to wrap */
  33. private final Closure iClosure;
  34. /**
  35. * Factory method that performs validation.
  36. *
  37. * @param closure the closure to call, not null
  38. * @return the <code>closure</code> transformer
  39. * @throws IllegalArgumentException if the closure is null
  40. */
  41. public static Transformer getInstance(Closure closure) {
  42. if (closure == null) {
  43. throw new IllegalArgumentException("Closure must not be null");
  44. }
  45. return new ClosureTransformer(closure);
  46. }
  47. /**
  48. * Constructor that performs no validation.
  49. * Use <code>getInstance</code> if you want that.
  50. *
  51. * @param closure the closure to call, not null
  52. */
  53. public ClosureTransformer(Closure closure) {
  54. super();
  55. iClosure = closure;
  56. }
  57. /**
  58. * Transforms the input to result by executing a closure.
  59. *
  60. * @param input the input object to transform
  61. * @return the transformed result
  62. */
  63. public Object transform(Object input) {
  64. iClosure.execute(input);
  65. return input;
  66. }
  67. /**
  68. * Gets the closure.
  69. *
  70. * @return the closure
  71. * @since Commons Collections 3.1
  72. */
  73. public Closure getClosure() {
  74. return iClosure;
  75. }
  76. }