View Javadoc

1   package com.lexicalscope.fluentreflection;
2   
3   /*
4    * Copyright 2011 Tim Wood
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License. 
17   */
18  
19  import java.util.List;
20  
21  import org.hamcrest.Description;
22  import org.hamcrest.Factory;
23  import org.hamcrest.Matcher;
24  
25  /**
26   * Inspired by LambdaJ
27   * 
28   * @author tim
29   * 
30   * @param <T>
31   */
32  final class MatcherOr<T> extends ReflectionMatcher<T> {
33      private final List<? extends Matcher<? super T>> matchers;
34  
35      private MatcherOr(final List<? extends Matcher<? super T>> matchers) {
36          this.matchers = matchers;
37      }
38  
39      /**
40       * {@inheritDoc}
41       */
42      @Override
43      public boolean matchesSafely(final T item) {
44          for (final Matcher<? super T> matcher : matchers) {
45              if (matcher.matches(item)) {
46                  return true;
47              }
48          }
49          return false;
50      }
51  
52      @Override
53      public void describeTo(final Description description) {
54          for (int i = 0; i < matchers.size(); i++) {
55              description.appendDescriptionOf(matchers.get(i));
56              if (i + 1 < matchers.size()) {
57                  description.appendText(" or ");
58              }
59          }
60      }
61  
62      /**
63       * Creates an or matcher combining all the passed matchers
64       * 
65       * @param matchers
66       *            The matchers to be put in or
67       * @return A matcher that return true if at least one of the matchers return
68       *         true
69       */
70      @Factory
71      public static <T> MatcherOr<T> orOf(final List<? extends Matcher<? super T>> matchers) {
72          return new MatcherOr<T>(matchers);
73      }
74  }