Skip to content

Commit 718ba63

Browse files
author
nat.pryce
committed
Added template methods so generic subclasses can change the automagical-reflectomatic way that the concrete type parameter is found.
1 parent 72e743a commit 718ba63

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

hamcrest-core/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
*
1111
* @param <T>
1212
* @author Neil Dunn
13+
* @author Nat Pryce
1314
*/
1415
public abstract class TypeSafeDiagnosingMatcher<T> extends BaseMatcher<T> {
1516
private final Class<?> expectedType;
@@ -31,28 +32,31 @@ public final boolean matches(Object item) {
3132
&& matchesSafely((T) item, new Description.NullDescription());
3233
}
3334

34-
@SuppressWarnings("unchecked")
3535
@Override
36+
@SuppressWarnings("unchecked")
3637
public final void describeMismatch(Object item, Description mismatchDescription) {
3738
matchesSafely((T) item, mismatchDescription);
3839
}
39-
40-
private static Class<?> findExpectedType(Class<?> fromClass) {
40+
41+
private Class<?> findExpectedType(Class<?> fromClass) {
4142
for (Class<?> c = fromClass; c != Object.class; c = c.getSuperclass()) {
4243
for (Method method : c.getDeclaredMethods()) {
43-
if (isMatchesSafelyMethod(method)) {
44-
return method.getParameterTypes()[0];
44+
if (canObtainExpectedTypeFrom(method)) {
45+
return obtainExpectedTypeFrom(method);
4546
}
4647
}
4748
}
48-
49+
4950
throw new Error("Cannot determine correct type for matchesSafely() method.");
5051
}
51-
52-
private static boolean isMatchesSafelyMethod(Method method) {
52+
53+
protected boolean canObtainExpectedTypeFrom(Method method) {
5354
return method.getName().equals("matchesSafely")
5455
&& method.getParameterTypes().length == 2
5556
&& !method.isSynthetic();
5657
}
57-
58+
59+
protected Class<?> obtainExpectedTypeFrom(Method method) {
60+
return method.getParameterTypes()[0];
61+
}
5862
}

0 commit comments

Comments
 (0)