Why this happened? One line in the code works well while the other similar line doesn't. Does the automatic type cast only happen in certain conditions? I have tried to assign gt.echoV() to an Object and it works well; but when I assign it to a String, the same error will come out again.
public class GeneMethodTest {
public static void main(String... args) {
GeneMethodTest gt = new GeneMethodTest();
gt.<String>echoV(); //this line works well
gt.<String>echoV().getClass();//this line leads to a type cast exception
}
public <T> T echoV() {
T t=(T)(new Object());
return t;
}
}
gt.<String>echoV().getClass();
produces the equivalent of the following sequence of operations:
// Inside echoV
Object t = new Object(); // Note that this is NOT a String!
Object returnValue = t;
// In main
String stackTemp = (String) returnValue; // This is the operation that fails
stackTemp.getClass();
What you get "for free" with generics is that (String)
cast. Nothing else.
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