File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package org .hamcrest ;
22
3+ import java .lang .reflect .Method ;
4+
35/**
46 * Convenient base class for Matchers that require a non-null value of a specific type.
57 * This simply implements the null check, checks the type and then casts.
810 */
911public abstract class TypeSafeMatcher <T > implements Matcher <T > {
1012
13+ private Class expectedType ;
14+
1115 /**
1216 * Subclasses should implement this. The item will already have been checked for
1317 * the specific type and will never be null.
1418 */
1519 protected abstract boolean matchesSafely (T item );
1620
21+ protected TypeSafeMatcher () {
22+ // Determine what T actually is.
23+ for (Method method : getClass ().getMethods ()) {
24+ if (method .getName ().equals ("matchesSafely" ) && !method .isSynthetic ()) {
25+ expectedType = method .getParameterTypes ()[0 ];
26+ break ;
27+ }
28+ }
29+ if (expectedType == null ) {
30+ throw new Error ("Cannot determine correct type for matchesSafely() method." );
31+ }
32+ }
33+
1734 /**
1835 * Method made final to prevent accidental override.
1936 * If you need to override this, there's no point on extending TypeSafeMatcher.
2037 * Instead, implement the Matcher interface directly.
2138 */
2239 @ SuppressWarnings ({"unchecked" })
2340 public final boolean matches (Object item ) {
24- return item != null && matchesSafely ((T ) item );
41+ return item != null
42+ && expectedType .isInstance (item )
43+ && matchesSafely ((T ) item );
2544 }
26-
45+
2746}
Original file line number Diff line number Diff line change @@ -38,4 +38,12 @@ public void testIsNullSafe() {
3838 createMatcher ().matches (null );
3939 }
4040
41+ public void testCopesWithUnknownTypes () {
42+ // should not throw ClassCastException
43+ createMatcher ().matches (new UnknownType ());
44+ }
45+
46+ public static class UnknownType {
47+ }
48+
4149}
You can’t perform that action at this time.
0 commit comments