简体   繁体   中英

A bad casting to Generics parameter type does not throw ClassCastException in Java

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, ie int i = Test.<Integer> get(); is equivalent to:

Object o = Test.get();
int i = ((Integer) o).intValue();

这可能是因为在运行时,jvm不知道T是什么,并且将其视为Object ,因此,在知道泛型类型的情况下,将继续对Integer进行实际转换,因此这里是: int i = Test.<Integer>get();

Generics in java are implemented with erasures. This means that at runtime java has no meaning of the generic types used and uses Object instead.

At runtime "thing" is an Object, and assigning anything to an Object doesn't provoke any error.

public static <T> T get()

insists that the result will be of caller type. Thus line

int i = Test.<Integer>get();

forces Integer to obj to be cases as Integer:

thing = (T)mObj;

But mObj is an instance of String.

To implement generics, the Java compiler applies type erasure to:

Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded.

ref: http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

Hence, the code

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;
}

at runtime should erase to be

public static Object get() {
Object thing = null;
try {
    // Expected ClassCastException here
    thing = (Object)mObj;
} catch ( ClassCastException e ) {
    System.out.println("This will *not* be printed");
}
return thing;
}

since T is unbounded. Understand this, then it is easy to explain the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM