Arjun
Arjun

Reputation: 1262

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?

EDIT

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

        }
        void showType1(){
            System.out.println(ob1.getClass().getName());
        }

    }
public class GenDemo {

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

    }

}



output:

Exception in thread "main" java.lang.NullPointerException
        at Gen.showType1(Gen.java:13)
        at GenDemo.main(GenDemo.java:7)

Why same method call on ob1 doesn't work?

Upvotes: 1

Views: 2712

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

obj refers to an actual object (of type String). At runtime, non-primitive objects carry around their type information with them, which is what getClass() returns.

This isn't really affected by generics (not least because generics don't exist at runtime). It's exactly the same as if you'd done something like this:

Object ob = "abcd";
System.out.println(ob.getClass().getName());

Upvotes: 4

Related Questions