Test if object is instanceof a parameter type

前端 未结 6 467
再見小時候
再見小時候 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<T> 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).

    0 讨论(0)
  • 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<T> type = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                      .getActualTypeArguments()[0];
      if (type.isInstance(obj)) {
          ...
      }
    
    0 讨论(0)
  • 2020-12-04 21:12

    You could try this,

    // Cast your object to the generic type.
    T data = null;
    try {
        data = (T) obj;
    } catch (ClassCastException cce) {
        // Log the error.
    }
    
    // Check if the cast completed successfully.
    if(data != null) {
        // whatever....
    }
    
    0 讨论(0)
  • 2020-12-04 21:13

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

    Class<T> type; //maybe passed to the method
    if ( type.isInstance(obj) ) {
       T t = type.cast(obj);
       // ...
    }
    
    0 讨论(0)
  • 2020-12-04 21:19

    It would make more sense to put the restriction on where the type T is used to parametrise the Class type. When you pass the type in, instead of using something like Class<?>, you should use Class<? extends T>.

    0 讨论(0)
  • 2020-12-04 21:22

    The only way you can do this check is if you have the Class object representing the type:

    Class<T> type; //maybe passed into the method
    if ( type.isInstance(obj) ) {
       //...
    }
    
    0 讨论(0)
提交回复
热议问题