【发布时间】:2020-02-12 09:11:28
【问题描述】:
我是 Java 新手,正在学习 Hamcrest 框架。
我看过Matcher接口的代码,看不懂matches(Object actual)的注释和方法签名。我希望它是matches(T actual),并使用泛型类型T 而不是接受所有内容的Object。
对于matches 方法:
public interface Matcher<T> extends SelfDescribing {
/**
* Evaluates the matcher for argument <var>item</var>.
*
* This method matches against Object, instead of the generic type T. This is
* because the caller of the Matcher does not know at runtime what the type is
* (because of type erasure with Java generics). It is down to the implementations
* to check the correct type.
*
* @param actual the object against which the matcher is evaluated.
* @return <code>true</code> if <var>item</var> matches, otherwise <code>false</code>.
*
* @see BaseMatcher
*/
boolean matches(Object actual);
阅读该方法上方的评论,表明这是故意的,我不明白为什么。我知道java中的类型擦除是什么。但是我仍然不明白为什么 Hamcrest 的设计者认为将 Object 作为输入而不是声明为通用的接口的通用类型更好
public interface Matcher<T> extends SelfDescribing
【问题讨论】:
标签: java generics matcher hamcrest