getClass() of a Generic Method Parameter in a Java

后端 未结 2 1734

The following Java method fails to compile:

 void foo(T t)
{
    Class klass = t.getClass();
}

Error

2条回答
  •  执笔经年
    2021-02-14 18:06

    It is kind of silly. It would have been better, for most use cases, if x.getClass() returns Class, instead of the erased Class.

    The erasure is the cause of loss of information, making your code, apparently safe, fail to compile. t.getClass() returns Class, and |T| = Number, so it returns Class.

    The erasure (mandated by the language spec) is to maintain theoretical correctness. For example

    List x = ...;
    Class c1 = x.getClass(); // ok
    Class> c2 = x.getClass(); // error
    

    Although c2 seems very reasonable, in Java, there is really no such class for List. There is only the class for List. So allowing c2 would be, theoretically incorrect.

    This formality created lots of problem in real world usages, where programmers can reason that Class is safe for their purposes, but have to cope with the erased version.

    You can simply define your own getClass that returns the un-erased type

    static public  Class getFullClass(X x)
        return (Class)(Class) x.getClass() ;
    
     void foo(T t)
    {
        Class klass = getFullClass(t);
    }
    

提交回复
热议问题