May 15

Short answer is you can’t.

Generics use type erasure which means the compiler removes all information related to the parameters within the class. This is done to maintain binary compatibility with classes that were created before generics.

public class MyClass<T> {
    public void myMethod(Object item) {
        if (item instanceof T) {     // Compiler error
            // do something
        }
        Class<T> c1 = T.class;       // Compiler error
        Class<T> c2 = T.getClass();  // Compiler error
        T item2 = new T();           // Compiler error
        T[] array = new T[10];       // Compiler error
        T o = (T) new Object();      // Unchecked cast warning
    }
}

written by objects \\ tags: ,


Leave a Reply

You must be logged in to post a comment.