Determining the Type for a generic method parameter at runtime

后端 未结 2 591
忘了有多久
忘了有多久 2021-01-13 19:27

Given the a class with the following structure. I am trying to determine the type of the parameter T assigned by the caller of the generic method.

public cl         


        
2条回答
  •  半阙折子戏
    2021-01-13 20:18

    You can't, generics aren't available at runtime. If you had an instance of T, you could always check if T object was an instance of a specific class with instanceof.

    This is due to type erasure.

    An other way is to use the Class class as a parameter (see @ColinD's answer)

提交回复
热议问题