简体   繁体   English

获取通用变量的参数化类型类

[英]Get parameterized type class of a generic variable

public class Foo {

    public <T> void foo(final T t) {
        final Class<T> clazz = (Class<T>) t.getClass();
    }

}

I can not understand why t.getClass() return a Class<?> and not a Class<T> (or a Class<? extends T> ) and so why I need to make a cast. 我不明白为什么t.getClass()返回Class<?>而不返回Class<T> (或Class<? extends T> ),所以为什么需要进行强制转换。

In which way this cast can fail ? 这种转换会以哪种方式失败?

Generics in Java is implemented using type erasure. Java中的泛型使用类型擦除来实现。

The type T does not exist at runtime and the compiler substitutes the T with java.lang.Object . 类型T在运行时不存在,并且编译java.lang.Object替换T So the following method is actually compiled in bytecode: 因此,以下方法实际上是用字节码编译的:

public void foo(final Object t)

You should look up the term 'type erasure'. 您应该查找“类型擦除”一词。 The way Java does generics is to compile 'generic' code. Java做泛型的方法是编译“泛型”代码。 That is, it compiles code that will work with any type and does the type checking at compile time. 也就是说,它会编译将适用于任何类型的代码,并在编译时进行类型检查。

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

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