How to do `MyClass.class` in Java?

前端 未结 6 1279
有刺的猬
有刺的猬 2020-12-15 21:46

How can call public T doit(Class clazz); using MyClass.class as clazz where I can not instantiate or extend MyClas

6条回答
  •  不思量自难忘°
    2020-12-15 22:21

    Use List.class. Because of type erasure type parameters to Java classes are entirely a compile-time construct - even if List.class was valid syntax, it would be the exact same class as List.class, etc. Since reflection is by nature a runtime thing, it doesn't deal well with type parameters (as implemented in Java).

    If you want to use the Class object to (for example) instantiate a new List instance, you can cast the result of that operation to have the appropriate type parameter.

    List list = (List)(ArrayList.class.newInstance());
    

提交回复
热议问题