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.Matcher;
23  
24  /**
25   * Inspired by LambdaJ
26   * 
27   * @author tim
28   * 
29   * @param <T>
30   */
31  final class MatcherAnd<T> extends ReflectionMatcher<T> {
32      private final List<? extends Matcher<? super T>> matchers;
33  
34      private MatcherAnd(final List<? extends Matcher<? super T>> matchers) {
35          this.matchers = matchers;
36      }
37  
38      /**
39       * {@inheritDoc}
40       */
41      @Override
42      public boolean matchesSafely(final T item) {
43          for (final Matcher<? super T> matcher : matchers) {
44              if (!matcher.matches(item)) {
45                  return false;
46              }
47          }
48          return true;
49      }
50  
51      @Override
52      public void describeTo(final Description description) {
53          for (int i = 0; i < matchers.size(); i++) {
54              description.appendDescriptionOf(matchers.get(i));
55              if (i + 1 < matchers.size()) {
56                  description.appendText(" and ");
57              }
58          }
59      }
60  
61      /**
62       * Creates an and matcher combining all the passed matchers
63       * 
64       * @param matchers
65       *            The matchers to be put in and
66       * @return A matcher that return true if all of the matchers return true
67       */
68      public static <T> MatcherAnd<T> andOf(final List<? extends Matcher<? super T>> matchers) {
69          return new MatcherAnd<T>(matchers);
70      }
71  }