There is a method in hamcrest library:
package org.hamcrest.core
...
public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second) {
List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super T>>(2);
matchers.add(first);
matchers.add(second);
return allOf(matchers);
}
In my code, I call this method with first
being Matcher<Object>
and second
being Matcher<SomeException>
.
And now:
<T>
Matcher<SomeException>
.<T>
Matcher<SomeException>
.<T>
Matcher<Object>
The question is, what <T>
should be in such case?
My understanding is, that there is a bug in javac 1.6 and it should be Matcher<SomeException>
, as this is a common type for input arguments (SomeException is a subtype of Object) and then, it is 100% sure, that returned Matcher will be Matcher<SomeException>
.
Am I right? And is there any way to force javac 1.6 to behave properly?
The compiler will do an inference based on actual arguments. It will start out with the initial constraints of Matcher<Object> << Matcher<? super T>
and Matcher<SomeException> << Matcher<? super T>
. From that it will infer the constraints T << Object
and T << SomeException
. Object
will be eliminated when the minimal erased candidate set is constructed. The remaining candidate SomeException
will (eventually :D) be substituted for T
.
So far we've shown eclipse and JDK7 behave correctly in this case. I don't think there is any way to force javac to behave correctly as well. You can either explicitly state the type argument or use JDK7 (specifying source and target to be 6).
There are two things you should consider:
First you could use it like this: CoreMatcher.<SomeException>allOf(...)
which would explicitly set T
.
Second, due to type-erasure, as run-time you ALWAYS have a Matcher<Object>
. So in either case the run-time behavior is the same.
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