Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and ClassCastException

Tags:

java

generics

Given the following piece of code:

public class ClassCastTest {

    private static class GenericHolder<T> {
        private T object;

        public GenericHolder(Object object) {
            this.object = (T) object;
            System.out.println(getObject());
        }

        public T getObject() {
            return object;
        }
    }

    public static void main(String[] args) {
        GenericHolder<String> foo = new GenericHolder<>(3l);
        System.out.println(foo.getObject());
    }

}

Why does Java throw a ClassCastException in the second line of the main-method instead of the second line of the GenericHolder?

like image 220
Frame91 Avatar asked Jan 22 '26 04:01

Frame91


1 Answers

Because of the way generics are implemented in the language, your cast to (T) doesn't actually do anything. It's only when you use a generic type in a way that actually gets out a concrete type -- here, System.out.println expects a String and it does the cast to get it -- that the runtime actually does any casting.

As far as the Java runtime is concerned, there's no difference between a GenericHolder<String> and a GenericHolder<Integer>; they both hold an Object. Java just inserts casts anywhere you get a concrete type out of a generic type.

Research type erasure for more details.

like image 83
Louis Wasserman Avatar answered Jan 26 '26 12:01

Louis Wasserman