How to get the class of type variable in Java Generics

前端 未结 7 1419
北恋
北恋 2021-02-01 17:24

I\'ve seen similar questions but they didnt help very much.

For instance I\'ve got this Generic Class:

public class ContainerTest
{

    public          


        
7条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 18:14

    No. It is not possible because of type erasure (the type parameters are compiled as Object + type casts). If you really need to know/enforce the type in runtime you may store a reference to a Class object.

    public class ContainerTest {
       private final Class klass;
       private final List list = new ArrayList();
    
       ContainerTest(Class klass) {
         this.klass = klass;
       }
    
       Class getElementClass() {
         return klass;
       }
    
       void add(T t) {
          //klass.cast forces a runtime cast operation
          list.add(klass.cast(t));
       }
    }
    

    Use:

    ContainerTest c = new ContainerTest<>(String.class);
    

提交回复
热议问题