Test if object is instanceof a parameter type

前端 未结 6 477
再見小時候
再見小時候 2020-12-04 21:02

Is there a way to determine if an object is an instance of a generic type?

public  test(Object obj) {
    if (obj instanceof T) {
        ...
    }
         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 21:12

    If you don't want to pass Class type as a parameter as mentioned by Mark Peters, you can use the following code. Kudos to David O'Meara.

      Class type = (Class) ((ParameterizedType) getClass().getGenericSuperclass())
                      .getActualTypeArguments()[0];
      if (type.isInstance(obj)) {
          ...
      }
    

提交回复
热议问题