Test if object is instanceof a parameter type

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

    To extend the sample of Mark Peters, often you want to do something like:

    Class type; //maybe passed to the method
    if ( type.isInstance(obj) ) {
       T t = type.cast(obj);
       // ...
    }
    

提交回复
热议问题