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

257
April 21, 2018, at 4:17 PM

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?

Answer 1

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());
Rent Charter Buses Company
READ ALSO
Update x- and y-coordinates on graph (JavaFX)

Update x- and y-coordinates on graph (JavaFX)

I'm having trouble at refreshing the x- and y-coordinates for a graphI know I can generate a graph and I know my ChoiceBox works and changes the value

182
How to create generic method that acts differently depending on the T?

How to create generic method that acts differently depending on the T?

What is the best way to create a generic method that acts differently depending on the given type without using if statements that check what type is that?

230
JPA Repository and constructor with varargs

JPA Repository and constructor with varargs

It is possible to use constructor of varargs in @Query (orgspringframework

654
implementation of template method pattern in the real world scenario

implementation of template method pattern in the real world scenario

I have requirement as below to build report building system

194