Search code examples
javagenericstype-erasure

Why was the information saved after the type erasure?


class Generic<T> {
    void method(T t) {
        print(t.getClass().getSimpleName());
    }
}
public class Program {
    static public void main(String[] args) {
        Generic<String> g = new Generic1<>();
        g.method(new String());
    }
}

As expected, the output is String. Why was the information about type saved if the type erasure was happened? If I understand it correctly, the output should have been Object.


Solution

  • This has nothing to do with generics.

    Each object knows it class object. You are getting "String" as output because this simply is the runtime class of a string object (which - by the way - you are creating).