为什么在Java Generics中将`<T> Type`作为返回类型而不是`Type <T>`?

tow*_*owi 8 java generics return-type hamcrest

我只写了一个简单的JUnit MatcherassertThat()要求仿制药,当然.

通过一点点运气,我发现了正确的语法返回类型static <T>Matcher not(Matcher<T> m)...,虽然我不明白为什么

  • 返回类型中<T>Matcher
  • 参数列表Matcher<T>

为什么它<T>Matcher在返回类型?这背后的概念是什么?

我来自C++,可以很好地处理它的模板.我知道Generics的工作方式不同,但这就是为什么这让我感到困惑.

这是我自己的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 ... */
}
Run Code Online (Sandbox Code Playgroud)

Jop*_*ops 11

Towi我希望这个例子有所帮助.

在此输入图像描述

上面的插图是对问题标题的直接回答:为什么它<T>Type是Java泛型中的返回类型而不是Type<T>

在Towi的例子中还有几个额外的要点,请参阅评论追踪.

  • 很酷的回答^^但是,应该提到的是(a)方法声明的类型参数T隐藏类的类型参数T和(b)返回类型匹配器在这种情况下是原始类型. (2认同)

wol*_*tle 10

你真的想要

static <T> Matcher<T>
Run Code Online (Sandbox Code Playgroud)

您需要第一个'T'来声明泛型方法的类型.第二个'T'是Matcher类的类型参数.