如何在Java中重用常见的扩展接口方法?

时间:2017-01-25 10:13:41

标签: java inheritance fluent-interface

我将这三个接口作为Fluent Interface API的一部分(其中发生了很多方法链接):

    interface VerifierA extends VerifierC {

      VerifierA method1();
      // other methods elided
    }

    interface VerifierB extends VerifierC {
     VerifierB method1();
       // other methods elided
    }

   interface VerifierC {
   VerifierA commonMethod();
   }

通过将commonMethod()声明为VerifierA,我可以将方法链接起来 commonMethod().method1()但不是commonMethod().method2();

我如何commonMethod() VerifierC根据需要返回VerifierA或VerifierB?

1 个答案:

答案 0 :(得分:2)

你可以用泛型来解决它:

interface VerifierA extends VerifierC<VerifierA> {
     VerifierC<VerifierA> method1();
}

interface VerifierB extends VerifierC<VerifierB> {
    VerifierC<VerifierB> method1();
}

interface VerifierC<T> {    
    T commonMethod();
}