Frage

I just wrote a simple JUnit Matcher for assertThat() which requires Generics, of course.

By a bit of luck I found the right syntax for the return type of static <T>Matcher not(Matcher<T> m)..., although I don't understand why

  • in the return type its <T>Matcher and
  • in the argument list its Matcher<T>

Why is it <T>Matcher in the return type? What is the concept behind this?

I am coming from C++ and can handle its Templates there quite well. I know that Generics work differently, but that's why this is confusing to me.

Here is my own Matcher class. Look at the static helper 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 ... */
}
War es hilfreich?

Lösung 2

You really want

static <T> Matcher<T>

You need the first 'T' to declare the type for the generic method. The second 'T' is the type parameter for the Matcher class.

Andere Tipps

Towi I hope this illustration helps.

enter image description here

The above illustration is a direct response to the question's title: Why is it <T>Type as return type in Java Generics and not Type<T>?

There are several more additional points to consider in Towi's example, see comment trail.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top