Skip to content

Commit 9282193

Browse files
author
joeretro
committed
Made all TypeSafeMatchers actually type safe :)
1 parent 0d7077d commit 9282193

2 files changed

Lines changed: 29 additions & 2 deletions

File tree

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package 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.
@@ -8,20 +10,37 @@
810
*/
911
public 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
}

‎src/unit-test/org/hamcrest/AbstractMatcherTest.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)