So, I have rather esoteric question. I'm trying to create a somewhat generic, but typed property collection system. It's reliant on a core assumption that seems to be erroneous. The code illustrates the issue:
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 {
// actual ClassCastException reported HERE
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 {
// Expected ClassCastException here
thing = (T)mObj;
} catch ( ClassCastException e ) {
System.out.println("This will *not* be printed");
}
return thing;
}
// This added in the edit
public static Integer getInt() {
return (Integer)mObj;
}
}
After compiling and running the output is
This should print
Why isn't the exception caught earlier?
In the static method "get", I'm attempting to cast to the generic parameter type T. The underlying member (mObj) is of String type. In the first invocation, the Generic parameter is of compatible type, so the app prints the string appropriately.
In the second invocation, the Generic parameter is of type Integer. Thus, the cast in the get method should fail. And I would hope it would throw a ClassCastException (printing the statement "This will *not* be printed".) But this isn't what happens.
Instead, the casting exception is thrown after the get method returns when the returned value is attempted to be assigned to the variable "i". Here's the question:
What is the explanation for this delayed casting error?
** EDIT ** For the sake of fun and completeness, I added a non-generic getInt method to illustrate the response I was hoping to get. Amazing what happens when the compiler knows type.
It's because the cast in the get
method (which should generate a compiler warning) is an unchecked cast. The compiler does not know what T
is when you call thing = (T) mObj;
so it cannot know if the cast should not compile.
After compilation, and due to type erasure, the bytecode generated invokes the method get
which returns an Object
(T
is erased and replaced with Object
) and the cast is simply translated to:
Object thing = null;
try {
thing = mObj;
The check is being done after the result is returned from the get
method, i.e. int i = Test.<Integer> get();
is equivalent to:
Object o = Test.get();
int i = ((Integer) o).intValue();
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