Every once in a while, I feel I don't know Java at all.. I recently found this strange behavior of Java type casting:
public static void main(String[] args) {
String res = get();
System.out.println(res);
}
public static <T> T get() {
Object longObj = Long.valueOf("0");
T casted = (T) longObj;
System.out.println("longObj=" + longObj.getClass());
System.out.println("casted=" + casted.getClass()); // <-- Why the type of "casted" is Long instead of String???
return casted;
}
The output is:
longObj=class java.lang.Long
casted=class java.lang.Long
Exception in thread "main" java.lang.ClassCastException: java.lang.Long
cannot be cast to java.lang.String
at com.apple.geo.coreloc.Test.main(Test.java:5)
My confusion is: Why variable casted
has type of Long
? Shouldn't it be casted to type T
, that is String
?
Following is why I thought it should be String
:
- At runtime,
String res = get()
hints get() method to return a String T casted = (T) longObj;
should try to type cast Long to a String (I expect an exception here, but there isn't..)