1
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.

luckystrrrike
  • 245
  • 1
  • 10
  • At runtime `t` is defined, it has a type. Some reading: https://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens?rq=1 –  Aug 28 '16 at 13:15
  • Passing in (or storing) an instance of a class is the classic way to get around type erasure. – Andy Turner Aug 28 '16 at 13:27

2 Answers2

8

For the same reason that this works:

            Object s = new String();
// Note ----^^^^^^
            System.out.println(s.getClass().getSimpleName());

The object still knows what it is and can tell us when we ask it via getClass.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
3

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).

Seelenvirtuose
  • 19,157
  • 6
  • 34
  • 57