Search code examples
javaclassinterfaceinstanceof

How to check if object implements particular interface, but not the descendants of this interface, in Java


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


Solution

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