-1

Consider this sample:

private <T> void m(Class<? extends T> k, Set<Class<? extends T>> sk) {
    Class<?> ku = k;
    Set<Class<?>> sku = sk; // <-- Type mismatch: cannot convert from
                            //     Set<Class<? extends T>> to Set<Class<?>>
}

In other words, I can assign a Class<? extends T> to a Class<?> for some arbitrary T but not a Set<Class<? extends T>> to a Set<Class<?>>.

It probably has something to do with some limitation on covariance/contravariance, but what?

I could introduce a cast: Class.class::cast would do it. But is there a way to bend the compiler to my will with subtle type-fu rather than bashing it in the head with a cast?

4

1 に答える 1

3

aClass<? extends T>は a ですがClass<?>、 a は a でSet<Class<? extends T>>はありませんSet<Class<?>>。同じ理由で、 a は aDogですがAnimal、aList<Dog>は a ではありませんList<Animal>。ここで、? extends Tは と同じ役割をDog持ち?、 と同じ役割を果たしますAnimal

これを正しくコンパイルするに? extendsは、前にが必要です。Class

Set<? extends Class<?>> sku = sk;
于 2015-10-05T22:39:08.783 に答える