开发者

Java Generics Type Casting

Lets say...

<T, S extends T> void work(final Class<T> type, fin开发者_如何学JAVAal S object) {}

or

<T> void work(final Class<T> type, final T object) {}

How can I pass following parameters to work()?

final Class<?> type = <not null> // This is actually an reflection output.
final Object object = <not null>

assert type.isInstance(object); // this is absolutely guaranteed

work(type, type.cast(object)); // compile error; how can I do this?
work(type, object); // compile error; how can I do this?


You'd need a Class<T> for this to work, but you can get that. Once you have that, you can simply do this:

work(type, type.cast(object));

Now, since you've got a Class<?> you can't simply assign it to a Class<T>, but you can work around this by providing an additional method:

<T> void checkedWork(final Class<T> type, final Object object) {
    work(type, type.cast(object));
}


Change final Class<?> type to final Class<Object> type (or to whatever concrete type you have). In your definition you have S extends T but if you pass in Class<?> you'd get T = ? and the compiler could not check whether Object extends ? (since ? could be anything).

Edit:

Alternatively, change work to <T, S> void work(final Class<T> type, final S object) {}.


The compiler cannot check that the object is an instance of type. You can do this at runtime as you have done. The simplest way to get this to compile is to use

final Class type = <not null>

This will give you a warning that the type is unchecked.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜