Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving peculiar 'unchecked cast' warning

Tags:

java

generics

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?

like image 884
otoomey Avatar asked Mar 02 '18 15:03

otoomey


1 Answers

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.

like image 153
Elliott Frisch Avatar answered Oct 05 '22 16:10

Elliott Frisch