Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics unchecked cast - Possible to check at runtime?

// @SuppressWarnings("unchecked")
private <T> T extractResult(Continuation continuation) {
    Object result = continuation.getAttribute("result");
    return (T) result;
}

Is it (at runtime) possible to verify that result can be cast to T?

like image 941
Kimble Avatar asked Feb 16 '26 06:02

Kimble


2 Answers

No. To check at runtime, you need an instance of a class, so that you can use isAssignableFrom. You don't have access to this using T due to type erasure.

like image 166
Matthew Farwell Avatar answered Feb 17 '26 18:02

Matthew Farwell


Not within this method. All type information related to T is erased by the compiler.

like image 36
Lukas Eder Avatar answered Feb 17 '26 20:02

Lukas Eder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!