简体   繁体   English

getClass()。getName()如何返回通用类型的类名称?

[英]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. 我知道Java对泛型使用了类型擦除,并且Java文档说getClass()返回对象的运行时类,但随后程序打印了泛型的类名称。
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? 为什么对ob1相同方法调用不起作用?

obj refers to an actual object (of type String ). obj指的是实际对象(类型为String )。 At runtime, non-primitive objects carry around their type information with them, which is what getClass() returns. 在运行时,非原始对象随身携带其类型信息,这是getClass()返回的信息。

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM