1

I have a method in one of my utility classes that takes a collection and a class object, and returns an Iterable instance that can iterate over all members of the collection that are instances of the specified class. Its signature is:

public static <T> Iterable<T> iterable (
      Iterable<? super T> source, Class<T> requiredClass);

This works very well for most use cases, but now I need to use it with a generic class, Item<PROTOTYPE>. I understand that I cannot be certain that the items returned by the resulting iterator cannot be guaranteed to have any particular prototype, so I tried to cast its return as follows:

Iterable<Item<?>> allItems = (Iterable<Item<?>>) 
                            TypeCheckingIterator.iterable(source, Item.class);

Unfortunately this returns a compiler error "Cannot cast from Iterable<Item> to Iterable<Item<?>>"

Why can it not perform this cast when I can cast Item to Item<?> quite happily? Is there a way I can force it to make this cast, without having to cast the items returned by the iterators explicitly?

4

1 回答 1

2

You can use type erasure if you are sure its safe

Iterable<Item<?>> allItems = (Iterable<Item<?>>) (Iterable)
                        TypeCheckingIterator.iterable(source, Item.class);

or

Iterable<Item<?>> allItems =
                     TypeCheckingIterator.<Item<?>>iterable(source, Item.class);
于 2012-07-22T11:32:20.960 回答