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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With