开发者

Reflection and interfaces

开发者 https://www.devze.com 2023-04-10 16:11 出处:网络
I have a class that indirectly implements an interface (its superclass or super-duper class implements can implement ) and I want to know wheather a class i开发者_开发百科mplements an interface or not

I have a class that indirectly implements an interface (its superclass or super-duper class implements can implement ) and I want to know wheather a class i开发者_开发百科mplements an interface or not.

In coding terms :

      import java.lang.reflect.Type;

        class My implements MyName{

        }

        public class Tset extends My implements yourName{
        public static void main(String[] args) {
            Class[] allClassAndInterfaces = Tset.class.getInterfaces();
    //but allClassAndInterfaces is not giving me the MyName Interface 
    //although it gives me YourName Interface
System.out.println(ArrayUtils.toString(lits));
        }
}


There is a specific method in the Class class called isAssignableFrom which does what you want. In your case, this should return true:

 MyName.class.isAssignableFrom(My.class);


You could also use instanceof to check whether an (instance of a) class implements an interface or not.

Edit:

interface X { }

class A implements X { }

System.out.println(new A() instanceof X);  // <---- prints true
0

精彩评论

暂无评论...
验证码 换一张
取 消