Knowing type of generic in Java

后端 未结 7 1147
醉话见心
醉话见心 2020-12-03 16:17

I have a generic class, says :

MyClass

Inside a method of this class, I would like to test the type of T, for example :

         


        
7条回答
  •  没有蜡笔的小新
    2020-12-03 17:10

    You can't, normally, due to type erasure. See Angelika Langer's Java Generics FAQ for more details.

    What you can do is pass a Class into your constructor, and then check that:

    public MyClass
    {
        private final Class clazz;
    
        public MyClass(Class clazz)
        {
            this.clazz = clazz;
        }
    
        public void myMethod()
        {
            if (clazz == String.class)
            {
               ...
            }
        }
    }
    

    Note that Java does not allow primitives to be used for type arguments though, so int is out...

提交回复
热议问题