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
<T>Matcher
andMatcher<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 ... */
}
In other words, the T is an actual part of the syntax for Generics and it means that the paramter for the Class can be of variable type? <T> is the generic type. Maybe read the official tutorial. Yes, the angle-brackets with one (or more) types is the syntax for generics.
< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.
6 Answers. Show activity on this post. Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ).
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.
Towi I hope this illustration helps.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With