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. /**
  20. * Predicate implementation that returns the opposite of the decorated predicate.
  21. *
  22. * @since Commons Collections 3.0
  23. * @version $Revision: 1.6 $ $Date: 2004/05/31 16:43:17 $
  24. *
  25. * @author Stephen Colebourne
  26. */
  27. public final class NotPredicate implements Predicate, PredicateDecorator, Serializable {
  28. /** Serial version UID */
  29. static final long serialVersionUID = -2654603322338049674L;
  30. /** The predicate to decorate */
  31. private final Predicate iPredicate;
  32. /**
  33. * Factory to create the not predicate.
  34. *
  35. * @param predicate the predicate to decorate, not null
  36. * @return the predicate
  37. * @throws IllegalArgumentException if the predicate is null
  38. */
  39. public static Predicate getInstance(Predicate predicate) {
  40. if (predicate == null) {
  41. throw new IllegalArgumentException("Predicate must not be null");
  42. }
  43. return new NotPredicate(predicate);
  44. }
  45. /**
  46. * Constructor that performs no validation.
  47. * Use <code>getInstance</code> if you want that.
  48. *
  49. * @param predicate the predicate to call after the null check
  50. */
  51. public NotPredicate(Predicate predicate) {
  52. super();
  53. iPredicate = predicate;
  54. }
  55. /**
  56. * Evaluates the predicate returning the opposite to the stored predicate.
  57. *
  58. * @param object the input object
  59. * @return true if predicate returns false
  60. */
  61. public boolean evaluate(Object object) {
  62. return !(iPredicate.evaluate(object));
  63. }
  64. /**
  65. * Gets the predicate being decorated.
  66. *
  67. * @return the predicate as the only element in an array
  68. * @since Commons Collections 3.1
  69. */
  70. public Predicate[] getPredicates() {
  71. return new Predicate[] {iPredicate};
  72. }
  73. }