Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 681
Curds Avatar asked May 13 '16 10:05

Curds


1 Answers

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();
like image 156
M A Avatar answered Oct 31 '22 21:10

M A