给出下面的例子(使用JUnit和Hamcrest匹配器):

Map<String, Class<? extends Serializable>> expected = null;
Map<String, Class<java.util.Date>> result = null;
assertThat(result, is(expected));  

它不使用JUnit assertThat方法签名编译:

public static <T> void assertThat(T actual, Matcher<T> matcher)

编译器错误消息是:

Error:Error:line (102)cannot find symbol method
assertThat(java.util.Map<java.lang.String,java.lang.Class<java.util.Date>>,
org.hamcrest.Matcher<java.util.Map<java.lang.String,java.lang.Class
    <? extends java.io.Serializable>>>)

但是,如果我将assertThat方法签名更改为:

public static <T> void assertThat(T result, Matcher<? extends T> matcher)

然后进行编译工作。

所以有三个问题

Why exactly doesn't the current version compile? Although I vaguely understand the covariance issues here, I certainly couldn't explain it if I had to. Is there any downside in changing the assertThat method to Matcher<? extends T>? Are there other cases that would break if you did that? Is there any point to the genericizing of the assertThat method in JUnit? The Matcher class doesn't seem to require it, since JUnit calls the matches method, which is not typed with any generic, and just looks like an attempt to force a type safety which doesn't do anything, as the Matcher will just not in fact match, and the test will fail regardless. No unsafe operations involved (or so it seems).

作为参考,下面是assertThat的JUnit实现:

public static <T> void assertThat(T actual, Matcher<T> matcher) {
    assertThat("", actual, matcher);
}

public static <T> void assertThat(String reason, T actual, Matcher<T> matcher) {
    if (!matcher.matches(actual)) {
        Description description = new StringDescription();
        description.appendText(reason);
        description.appendText("\nExpected: ");
        matcher.describeTo(description);
        description
            .appendText("\n     got: ")
            .appendValue(actual)
            .appendText("\n");

        throw new java.lang.AssertionError(description.toString());
    }
}

当前回答

您的原始代码不能编译的原因是<?>的意思不是“任何扩展Serializable的类”,而是“一些未知但特定的扩展Serializable的类”。

例如,给定所编写的代码,将新的TreeMap<String, Long.class>()赋值给expected是完全有效的。如果编译器允许代码编译,assertThat()可能会中断,因为它期望的是Date对象,而不是它在映射中发现的Long对象。

其他回答

您的原始代码不能编译的原因是<?>的意思不是“任何扩展Serializable的类”,而是“一些未知但特定的扩展Serializable的类”。

例如,给定所编写的代码,将新的TreeMap<String, Long.class>()赋值给expected是完全有效的。如果编译器允许代码编译,assertThat()可能会中断,因为它期望的是Date对象,而不是它在映射中发现的Long对象。

首先,我要把你引向http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html——她做得非常棒。

基本思想是你用

<T extends SomeClass>

当实际参数可以是SomeClass或它的任何子类型时。

在你的例子中,

Map<String, Class<? extends Serializable>> expected = null;
Map<String, Class<java.util.Date>> result = null;
assertThat(result, is(expected));

您是说expected可以包含表示实现Serializable的任何类的Class对象。结果映射表示它只能保存Date类对象。

当你传递result时,你将T设置为精确的Map of String to Date类对象,它不会将Map of String匹配到任何可序列化的对象。

有一件事要检查——你确定你想要Class<Date>而不是Date?String到Class<Date>的映射在一般情况下听起来不是特别有用(它只能保存Date. Class作为值,而不是Date的实例)

至于泛化assertThat,其思想是该方法可以确保传入符合结果类型的Matcher。

我理解通配符的一种方法是认为通配符并没有指定给定泛型引用可以“拥有”的可能对象的类型,而是它与其他泛型引用兼容的类型(这听起来可能令人困惑…)因此,第一个答案的措辞非常具有误导性。

换句话说,List<?扩展Serializable>意味着您可以将该引用赋值给其他列表,其中类型为某个未知类型或Serializable的子类。不要认为它是一个单一的列表,可以容纳Serializable的子类(因为这是不正确的语义,会导致对泛型的误解)。

如果你使用

Map<String, ? extends Class<? extends Serializable>> expected = null;

我知道这是一个老问题,但我想分享一个例子,我认为它很好地解释了有界通配符。collections提供了以下方法:

public static <T> void sort(List<T> list, Comparator<? super T> c) {
    list.sort(c);
}

If we have a List of T, the List can, of course, contain instances of types that extend T. If the List contains Animals, the List can contain both Dogs and Cats (both Animals). Dogs have a property "woofVolume" and Cats have a property "meowVolume." While we might like to sort based upon these properties particular to subclasses of T, how can we expect this method to do that? A limitation of Comparator is that it can compare only two things of only one type (T). So, requiring simply a Comparator<T> would make this method usable. But, the creator of this method recognized that if something is a T, then it is also an instance of the superclasses of T. Therefore, he allows us to use a Comparator of T or any superclass of T, i.e. ? super T.