【问题标题】:How to check if object implements particular interface, but not the descendants of this interface, in Java如何在Java中检查对象是否实现特定接口,而不是该接口的后代
【发布时间】:2013-04-10 18:46:48
【问题描述】:

我有一个树形结构,其中一些节点必须只包含实现特定接口的对象。但是有接口扩展了该接口,并且实现它们的对象不应该包含在节点中。
所以我需要检查对象是否实现了严格的特定接口。

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

【问题讨论】:

  • 也许您可以为我们提供一个虚构名称的示例。更容易理解您要做什么。
  • 这似乎是个坏主意。如果Foo 是扩展Bar 的接口,那么Bar 应该在每个地方都可用,Foo 应该可用。
  • 也许 [instanceOf][1] 运算符可能有帮助? [1]:stackoverflow.com/questions/631099/…

标签: java class interface instanceof


【解决方案1】:

您可以使用http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getInterfaces()

但对我来说,你想做的事情就像修补写得不好的应用程序。对我来说,更好的方法是创建一个新接口(只有所需的对象才会实现)并使“树结构”节点需要该特定接口。

【讨论】:

  • 感谢您指出我的错误。在我的项目中,为节点创建单独的接口似乎是一项简单的任务。我以前怎么没想到?
【解决方案2】:

您可以使用getInterfaces 获取已实现接口的列表。

假设您已经将实例转换为所需的接口,您只需测试 yourInstance.getClass().getInterfaces().length==1

【讨论】:

    【解决方案3】:

    类实现 getInterfaces() 方法。它返回一个类[]。使用它,您可以迭代并进行比较,直到找到或未找到。 http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getInterfaces()

    【讨论】:

      【解决方案4】:

      您可以在节点上执行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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-03
        • 1970-01-01
        • 1970-01-01
        • 2012-12-29
        • 1970-01-01
        • 1970-01-01
        • 2011-07-06
        • 2012-03-06
        相关资源
        最近更新 更多