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.Predicate;
  19. import org.apache.commons.collections.Transformer;
  20. /**
  21. * Transformer implementation that calls a Predicate 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 PredicateTransformer implements Transformer, Serializable {
  30. /** Serial version UID */
  31. static final long serialVersionUID = 5278818408044349346L;
  32. /** The closure to wrap */
  33. private final Predicate iPredicate;
  34. /**
  35. * Factory method that performs validation.
  36. *
  37. * @param predicate the predicate to call, not null
  38. * @return the <code>predicate</code> transformer
  39. * @throws IllegalArgumentException if the predicate is null
  40. */
  41. public static Transformer getInstance(Predicate predicate) {
  42. if (predicate == null) {
  43. throw new IllegalArgumentException("Predicate must not be null");
  44. }
  45. return new PredicateTransformer(predicate);
  46. }
  47. /**
  48. * Constructor that performs no validation.
  49. * Use <code>getInstance</code> if you want that.
  50. *
  51. * @param predicate the predicate to call, not null
  52. */
  53. public PredicateTransformer(Predicate predicate) {
  54. super();
  55. iPredicate = predicate;
  56. }
  57. /**
  58. * Transforms the input to result by calling a predicate.
  59. *
  60. * @param input the input object to transform
  61. * @return the transformed result
  62. */
  63. public Object transform(Object input) {
  64. return (iPredicate.evaluate(input) ? Boolean.TRUE : Boolean.FALSE);
  65. }
  66. /**
  67. * Gets the predicate.
  68. *
  69. * @return the predicate
  70. * @since Commons Collections 3.1
  71. */
  72. public Predicate getPredicate() {
  73. return iPredicate;
  74. }
  75. }