Use of generic cast operation in Java

33 views Asked by At

Consider the following code snippet:

public static <T> T convertInstanceOfObject(Object o) {
    try {
        T rv = (T)o;
        return rv;
    } catch(java.lang.ClassCastException e) {
        return null;
    }
}
  • now here the line T rv = (T)o; shows that we are converting the object of type Object to a type T.
  • My doubt is that why the syntax needs a redundant (T) to be specified when it ultimately gets converted to the Object type at the runtime?
  • I mean - had the statement formation been T rv = o; the compiler would have understood the same thing. And the statement T rv = (T)o; is not doing any good afterall when (T) is being used as the casting operator.
0

There are 0 answers