有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么它在Java泛型中作为返回类型而不是类型?

我刚刚为assertThat()编写了一个简单的JUnit Matcher,当然它需要泛型

幸运的是,我为static <T>Matcher not(Matcher<T> m)...返回类型找到了正确的语法,尽管我不明白为什么

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

为什么返回类型中有<T>Matcher这背后的概念是什么

<>我来自C++,可以很好地处理它的模板EME>。我知道泛型的工作方式不同,但这就是为什么这让我感到困惑的原因

这是我自己的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 ... */
}

共 (2) 个答案

  1. # 1 楼答案

    托维:我希望这幅插图能有所帮助

    enter image description here

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

    <> Po>在ToWi的示例中,还有几个额外的要点要考虑,请参阅注释Trime.

  2. # 2 楼答案

    你真的想要吗

    static <T> Matcher<T>
    

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