Test if object is instanceof a parameter type

前端 未结 6 475
再見小時候
再見小時候 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:11

    This will only work (partly) if you have an object of type T. Then you can get the class of that object, see java.lang.Class and find if it's the same as the object in question.

    But note that this goes counter the very reason we have genrics: using a generic type is a way to say that you don't care what type it really is (up to upper and lower bounds that may be specified).

提交回复
热议问题