33import java .lang .reflect .Method ;
44
55/**
6- * TODO(ngd): Document
6+ * Convenient base class for Matchers that require a non-null value of a specific type
7+ * and that will report why the received value has been rejected.
8+ * This implements the null check, checks the type and then casts.
9+ * To use, implement <pre>matchesSafely()</pre>.
710 *
811 * @param <T>
12+ * @author Neil Dunn
913 */
1014public abstract class TypeSafeDiagnosingMatcher <T > extends BaseMatcher <T > {
1115 private final Class <?> expectedType ;
1216
1317 protected TypeSafeDiagnosingMatcher () {
14- expectedType = findExpectedType (getClass ());
15- }
16-
17- private static Class <?> findExpectedType (Class <?> fromClass ) {
18- for (Class <?> c = fromClass ; c != Object .class ; c = c .getSuperclass ()) {
19- for (Method method : c .getDeclaredMethods ()) {
20- if (isMatchesSafelyMethod (method )) {
21- return method .getParameterTypes ()[0 ];
22- }
23- }
24- }
25-
26- throw new Error ("Cannot determine correct type for matchesSafely() method." );
27- }
28-
29- private static boolean isMatchesSafelyMethod (Method method ) {
30- return method .getName ().equals ("matchesSafely" )
31- && method .getParameterTypes ().length == 2
32- && !method .isSynthetic ();
18+ this .expectedType = findExpectedType (getClass ());
3319 }
3420
3521 /**
@@ -50,4 +36,23 @@ public final boolean matches(Object item) {
5036 public final void describeMismatch (Object item , Description mismatchDescription ) {
5137 matchesSafely ((T ) item , mismatchDescription );
5238 }
39+
40+ private static Class <?> findExpectedType (Class <?> fromClass ) {
41+ for (Class <?> c = fromClass ; c != Object .class ; c = c .getSuperclass ()) {
42+ for (Method method : c .getDeclaredMethods ()) {
43+ if (isMatchesSafelyMethod (method )) {
44+ return method .getParameterTypes ()[0 ];
45+ }
46+ }
47+ }
48+
49+ throw new Error ("Cannot determine correct type for matchesSafely() method." );
50+ }
51+
52+ private static boolean isMatchesSafelyMethod (Method method ) {
53+ return method .getName ().equals ("matchesSafely" )
54+ && method .getParameterTypes ().length == 2
55+ && !method .isSynthetic ();
56+ }
57+
5358}
0 commit comments