Reputation: 1740
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
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
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
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
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