【发布时间】:2013-05-07 15:15:08
【问题描述】:
我刚刚为assertThat() 写了一个简单的JUnit Matcher,当然它需要泛型。
幸运的是,我为static <T>Matcher not(Matcher<T> m)... 的返回类型找到了正确的语法,虽然我不明白为什么
- 在返回类型它的
<T>Matcher和 - 在参数列表中是
Matcher<T>
为什么返回类型中是<T>Matcher?这背后的概念是什么?
我来自 C++,可以很好地处理它的 模板。我知道泛型的工作方式不同,但这就是为什么这让我感到困惑。
这是我自己的Matcher 课程。看静态助手not:
import org.hamcrest.*;
/** assertThat(result, not(hasItem("Something"))); */
class NotMatcher<T> extends BaseMatcher<T> {
/** construction helper factory */
static <T>Matcher not(Matcher<T> m) { //< '<T>Matcher' ???
return new NotMatcher<T>(m);
}
/** constructor */
NotMatcher(Matcher<T> m) { /* ... */ }
/* ... more methods ... */
}
【问题讨论】:
-
提示:在
<T>和Matcher之间添加一个空格。 -
@SotiriosDelimanolis 为什么?它是否有助于我掌握它背后的概念?
-
是的,没错。这不是返回类型。这是两个不同的东西。 docs.oracle.com/javase/tutorial/extra/generics/methods.html
标签: java generics return-type hamcrest