Reputation: 77
I have a tree structure, where some nodes must contain only objects implementing particular interface. But there is interfaces extending that interface, and objects, implementing them, should not be contained in nodes.
So i need to check if object implements strictly particular interface.
public interface IProcessCell {...}
public interface IMethodCell extends IProcessCell {...}
IProcessCell processInstance = new IProcessCell() {...}
IMethodCell methodInstance = new IMethodCell() {...}
/** Method implementing desired check */
public boolean check(IProcessCell instance) {...}
Method check must return true for processInstance, but false for methodInstance
Upvotes: 1
Views: 470
Reputation: 3707
You can do a getClass().getInterfaces()
on the node, then iterate through the returned classes and check how many are assignable from the particular interface you care about. So if you have:
interface A {
}
interface B extends A {
}
class NodeA implements A {
}
class NodeB implements B {
}
If you're looking for a node instance that just implements A you should be able to do:
new NodeA().getClass().getInterfaces();
new NodeB().getClass().getInterfaces();
and in each case check that 1) One of the interfaces is A, and 2) A.class.isAssignableFrom(interface)
returns false for the other returned interfaces.
Upvotes: 0
Reputation: 146
Class implements the getInterfaces() method. It returns a Class[]. Using this you could iterate and do a comparison until found or not found. http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getInterfaces()
Upvotes: 1
Reputation: 182
You can use http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getInterfaces()
but to me the thing you are trying to do is like patching up badly written app. To me, the better way is creating a new interface (which only desired object will implement) and making the "tree structure" nodes require that particular interface.
Upvotes: 3
Reputation: 382514
You can get the list of implemented interfaces using getInterfaces.
Assuming you already casted your instance to the desired interface, you just have to test that yourInstance.getClass().getInterfaces().length==1
Upvotes: 2