So, I have a pretty esoteric question. I am trying to create a somewhat general but typed data collection system. He relies on a basic assumption that seems erroneous. The code illustrates the problem:
import java.lang.Integer;
public class Test {
private static Object mObj = new String("This should print");
public static void main(String[] args ) {
String s = Test.<String>get();
System.out.println(s);
try {
int i = Test.<Integer>get();
} catch ( ClassCastException e ) {
System.out.println("Why isn't the exception caught earlier?");
}
int i2 = getInt();
}
public static <T> T get() {
T thing = null;
try {
thing = (T)mObj;
} catch ( ClassCastException e ) {
System.out.println("This will *not* be printed");
}
return thing;
}
public static Integer getInt() {
return (Integer)mObj;
}
}
After compiling and running the output
This should print
Why isn't the exception caught earlier?
In the static "get" method, I try to use the general parameter type T. The base member (mObj) is of type String. In the first call, the Generic parameter is of a compatible type, so the application prints the string accordingly.
Generic Integer. , get . , ClassCastException ( " * * ".) , .
, get , "i". :
?
** **
getInt, , . , , .