为什么它在Java泛型中作为返回类型而不是类型?
我刚刚为assertThat()
编写了一个简单的JUnit Matcher
,当然它需要泛型
幸运的是,我为static <T>Matcher not(Matcher<T> m)...
的返回类型找到了正确的语法,尽管我不明白为什么
- 在返回类型中其
<T>Matcher
和 - 在参数列表中其
Matcher<T>
为什么返回类型中有<T>Matcher
这背后的概念是什么
这是我自己的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 ... */
}
# 1 楼答案
托维:我希望这幅插图能有所帮助
上图是对问题标题的直接回应:为什么它在Java泛型中是
<> Po>在ToWi的示例中,还有几个额外的要点要考虑,请参阅注释Trime.<T>Type
返回类型而不是Type<T>
# 2 楼答案
你真的想要吗
您需要第一个“T”来声明泛型方法的类型。第二个“T”是Matcher类的类型参数