roirodriguez
roirodriguez

Reputation: 1740

How to if a given type implements some interface

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 represents a class which implements the IModelElement interface, anyone knows how is this achieved?

Upvotes: 0

Views: 108

Answers (4)

fgysin
fgysin

Reputation: 11913

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
}

Upvotes: 1

David Oliván
David Oliván

Reputation: 2725

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.
        }
    }
}

Upvotes: 0

Matthijs Bierman
Matthijs Bierman

Reputation: 1757

Using the instanceof operator?

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

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

Upvotes: 0

Ryan Stewart
Ryan Stewart

Reputation: 128799

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

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

Upvotes: 5

Related Questions