![](/img/trans.png)
[英]How to check in Java using JIntegra if COM object implements an interface?
[英]How to check if object implements particular interface, but not the descendants of this interface, in Java
我有一個樹形結構,其中某些節點必須僅包含實現特定接口的對象。 但是,存在擴展該接口的接口,並且實現它們的對象不應包含在節點中。
所以我需要檢查對象是否實現嚴格特定的接口。
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) {...}
方法檢查必須對processInstance返回true,但對methodInstance返回false
您可以使用http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getInterfaces()
但是對我來說,您要嘗試做的事情就像是修補寫得不好的應用程序一樣。 對我來說,更好的方法是創建一個新接口(只有所需的對象才能實現),並使“樹結構”節點需要該特定接口。
您可以使用getInterfaces獲取已實現接口的列表。
假定您已經將實例yourInstance.getClass().getInterfaces().length==1
到所需的接口,則只需測試一下yourInstance.getClass().getInterfaces().length==1
類實現getInterfaces()方法。 它返回一個Class []。 使用此方法,您可以迭代並進行比較,直到找到或找不到為止。 http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getInterfaces()
您可以在節點上執行getClass().getInterfaces()
,然后遍歷返回的類並檢查您可以從特定接口分配多少個類。 因此,如果您有:
interface A {
}
interface B extends A {
}
class NodeA implements A {
}
class NodeB implements B {
}
如果您正在尋找僅實現A的節點實例,則應該能夠做到:
new NodeA().getClass().getInterfaces();
new NodeB().getClass().getInterfaces();
並分別檢查1)接口之一是A,以及2) A.class.isAssignableFrom(interface)
對於其他返回的接口返回false。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.