Java检查子进程是否正在实现接口

时间:2016-05-19 10:26:53

标签: java interface polymorphism abstract

我想通过实现接口(不在子类中编写主体)来做一些事情

这就是我想要实现的目标:

interface I{
    void foo();
}

具有功能I的类:

class A extends C implements I{


}

没有功能的类I

class B extends C {

}

家长班:

class C implements I{
    @Override
    public void foo(){
        // if child is implementing interface dirctly it should do stuff
        // Skip this otherwise 
    }
}

但是如何检查我的A课程是否直接实施I界面?为此:

主:

class Main {
    public Main() {
        I classA = new A();
        classA.foo(); // do stuff

        I classB = new B(); // <- not crash because C is implementing I interface
        classB.foo(); // empty
    }
}

3 个答案:

答案 0 :(得分:3)

尝试if (A instanceof I)
这应该工作

答案 1 :(得分:2)

虽然这在多态性方面毫无意义,但您可以检查该类是否直接实现I

package example;

public class A extends B implements I{
    public static void main(String...args)
    {
        new A().foo();
        new B().foo();
        new C().foo();
    }
}
class B extends C{

} 
class C implements I{

    @Override
    public void foo() {
        boolean implementsDirectly = false;
        for (Class c : getClass().getInterfaces()) {
            if(c.getName().equals("example.I")) {
                implementsDirectly = true;
            }
        }
        if(implementsDirectly) {
            System.out.println("The class " + getClass().getName() +" does implement I directly in the class definition");
        } else {
            System.out.println("The class " + getClass().getName() +" does not implement I directly in the class definition");
        }
    }

}

interface I {
    void foo();
}

输出:

The class example.A does implement I directly in the class definition
The class example.B does not implement I directly in the class definition
The class example.C does implement I directly in the class definition

答案 2 :(得分:0)

如果您知道方法名称,可以使用反射检查它:

class Main {
  public main() throws Exception{
    I classA = new A();
    boolean implementsIByItself=true;
    try{
      classA.getClass().getDeclaredMethod("foo", new Class[0]);
    } catch (NoSuchMethodException nsme){
      //Exception will be thrown if A doesnt declare "foo"
      implementsIByItself=false;
    }

  }
}

getDeclaredMethod只会返回一个Method对象,如果它被调用的类不只是继承它,而是声明它。

请记住,这不是一个非常干净的方法,可能有更合适的解决方案。如果您依赖于知道哪个类通过覆盖方法来改变行为,那么您的问题在设计中看起来就像是一个缺陷。