How to get the class of type variable in Java Generics

前端 未结 7 1421
北恋
北恋 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:28

    There is no "clean" way to get the Generic Type argument from within the class. Instead, a common pattern is to pass the Class of the Generic Type to the constructor and keep it as an inner property juste as done in the java.util.EnumMap implementation.

    http://docs.oracle.com/javase/1.5.0/docs/api/java/util/EnumMap.html http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/EnumMap.java

    public class ContainerTest<T> {
    
        Class<T> type;
        T t;
    
        public ContainerTest(Class<T> type) {
            this.type = type;
        }
    
        public void setT(T t) {
            this.t = t;
        }
    
        public T getT() {
            return t;
        }
    
        public void doSomething() {
            //There you can use "type" property.
        }
    }
    
    0 讨论(0)
提交回复
热议问题