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;
}
}
(T)(new Object())is an unchecked cast - make sure to read up on what that is and its implications, along with type erasure.<String>in of itself has nothing to do with casting - it's just the type argument to the generic method.gt.<String>echoV()alone requires no cast to be inserted by the compiler, so that doesn't fail at runtime.