I have an object where the type of generic T
is lost at some point through a giant interface chain. I was wondering if it is possible to use a function to regain some type safety by checking the types:
private T metaData; // type of T is lost
public <R> R getMetaData(Class<R> className) {
assert className.isInstance(metaData);
return (R) metaData;
}
However, this implementation produces an "Unchecked cast: 'T' to 'R'" warning. Is there an implementation that avoids this warning, or is the only solution to suppress it?
You don't have to cast to R
with ()
, you could use the Class
directly instead. Like,
return className.cast(metaData);
which doesn't cause any warnings here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.