开发者

How to if a given type implements some interface

开发者 https://www.devze.com 2023-04-04 21:25 出处:网络
I\'ve got an IModelElement interface, and several classes implementing that interface. Somewhere in my code there\'s the following statement:

I've got an IModelElement interface, and several classes implementing that interface. Somewhere in my code there's the following statement:

Object childClass = request.getNewObjectType();

Here getNewObjectType() returns a Class object. I need to check if that Class objects represe开发者_C百科nts a class which implements the IModelElement interface, anyone knows how is this achieved?


Class.isAssignableFrom(), and if it's a Class, then request.getNewObjectType() should return Class, not Object.

if (IModelElement.isAssignableFrom((Class) childClass)) {
    // whatever
}


You can just try to cast the return value of request.getNewObjectType() to IModelElement. If there is not ClassCastException the returned object is of a class which implements the interface.

try {
  IModelElement temp = (IModelElement) request.getNewObjectType();
} catch (ClassCastException e) {
  // the interface is not implemented
}


Using the instanceof operator?

if(childClass instanceof Class) {
  (Class) child = (Class) childClass;
  child.method();
}

http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html


Try:

Object childClass = request.getNewObjectType();
if (childClass instanceof Class) {
    for (Class interfaceClass in ((Class)childClass).getInterfaces()) {
        if (interfaceClass.getCanonicalName().equals("org.xx.YourInterface")) {
            // Do some stuff.
        }
    }
}
0

精彩评论

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

关注公众号