samedi 21 avril 2018

How does getClass().getName() return class name of the generic type?

I know java uses type erasure for generics and java documentation says getClass() returns runtime class of the object, yet following program prints class name of the generic type.
code:

    public class Gen<T> {
        T ob;
        public Gen(T ob) {
            this.ob=ob;
        }
        void showType() {
            System.out.println("Type of T is "+ ob.getClass().getName());

        }

}


    public class GenDemo {

        public static void main(String[] args) {
            Gen<String> str = new Gen("abcd");
            str.showType();

        }

    }

output:
Type of T is java.lang.String

How does this program work? How is it getting runtime class of the non-reifiable type?





Aucun commentaire:

Enregistrer un commentaire