开发者

How to cast List<? extends Foo> to List<Foo>

Spring Batch's ItemWriter开发者_Python百科 interface is this:

write(List<? extends T> items); 

I'd like the ItemWriter to call a Service but my service has this:

process(List<T> items); 

AFAIK, Java Generics are strict about casting types within collections.


Just go ahead and cast it. For reading, List<? extends Foo> is certainly a List<Foo>, the cast is absolutely safe. You can wrap it with Collections.unmodifiableList() if you are paranoid.

List<? extends Foo> foos1 = ...;

@SuppressWarnings("unchecked")
List<Foo> foos2 = (List<Foo>)(List<?>)foos1;    


Ensure that your method receives an object that inherits from T, and then perform a cast.

Or change the signature of your method to be equal to the write method.


List<? extends Foo> list1 = ...
List<Foo> list2 = Collections.unmodifiableList(list1);

Reason why list2 has to be read-only view of list1 is nicely explained in an answer of Generics : List is same as List?


If your service allows ? extends T, then that's what the type should be. Currently, it says what's passed in must be exactly T.


Gennerics in Java helps you only in compilation time. You can cast anything, make sure that the value is castable for the new type.


Can't you just cast it since you know that if you've got a type that extends Foo that it is a Foo?
Something like this:

write(List<? extends Foo> items) {
    //noinspection unchecked
    process( (List<Foo>) items );
}

process(List<Foo> items) {
    // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜