Check if a generic T implements an interface

后端 未结 3 791
南旧
南旧 2021-02-05 07:28

so I have this class in Java:

public class Foo{
}

and inside this class I want to know if T implements certain interface.

The

相关标签:
3条回答
  • 2021-02-05 08:01

    Use isAssignableFrom()

    isAssignableFrom() determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

    if (SomeInterface.class.isAssignableFrom(T class)) {
      //do stuff
    }
    
    0 讨论(0)
  • 2021-02-05 08:02

    Generics, oddly enough, use extends for interfaces as well.1 You'll want to use:

    public class Foo<T extends SomeInterface>{
        //use T as you wish
    }
    

    This is actually a requirement for the implementation, not a true/false check.

    For a true/false check, use unbounded generics(class Foo<T>{) and make sure you obtain a Class<T> so you have a refiable type:

    if(SomeInterface.class.isAssignableFrom(tClazz));
    

    where tClazz is a parameter of type java.lang.Class<T>.

    If you get a parameter of refiable type, then it's nothing more than:

    if(tParam instanceof SomeInterface){
    

    but this won't work with just the generic declaration.

    1If you want to require extending a class and multiple interfaces, you can do as follows: <T extends FooClass & BarInterface & Baz> The class(only one, as there is no multiple inheritance in Java) must go first, and any interfaces after that in any order.

    0 讨论(0)
  • 2021-02-05 08:10

    you can check it using isAssignableFrom

    if (YourInterface.class.isAssignableFrom(clazz)) {
        ...
    }
    

    or to get the array of interface as

    Class[] intfs = clazz.getInterfaces();
    
    0 讨论(0)
提交回复
热议问题