Is this cast safe?
private <T> void foo(T value) {
final Class<T> aClass = (Class<T>) value.getClass();
}
Does a more elegant way exist to do this?
Is it possible to avoid unchecked cast warning?
Is this cast safe?
private <T> void foo(T value) {
final Class<T> aClass = (Class<T>) value.getClass();
}
Does a more elegant way exist to do this?
Is it possible to avoid unchecked cast warning?
You can suppress the compiler warning. See What is SuppressWarnings ("unchecked") in Java?
Compiler is warning you for a reason. value
can contain an object of some subtype of T
and there are important differences between Class<Parent>
and Class<Child>
. In your case, you can see that you are not doing anything unsafe, but the compiler just follows the rules.
Imagine if the method was slightly different and there was a way to get another value of type T
:
<T> void foo(T a, T b) {
final Class<T> aClass = (Class<T>) a.getClass();
// What can go wrong? casting T to T
T c = aClass.cast(b);
}
// but what if the two parameters are of different classes at runtime
foo(5, 5.5); // ClassCastException!
Or what if we allow Class<T>
to escape as a return value:
<T> Class<T> foo(T val) {
final Class<T> aClass = (Class<T>) val.getClass();
return aClass;
}
// uhoh is declared as Class<Number> but contains Class<Integer> at runtime
Class<Number> uhoh = foo(5);
// Ok to cast Double to Number but not to Integer
Number num = uhoh.cast(5.5); // ClassCastException!