How can I require a method argument in Java to implement multiple interfaces?

前端 未结 1 1220
星月不相逢
星月不相逢 2020-12-08 09:33

It\'s legal to do this in Java:

 void spew(Appendable x)
 {
     x.append(\"Bleah!\\n\");
 }

How can I do this (syntax not legal):

相关标签:
1条回答
  • 2020-12-08 09:58

    You could do it with generics:

    public <T extends Appendable & Closeable> void spew(T t){
        t.append("Bleah!\n");
        if (timeToClose())
            t.close();
    }
    

    Your syntax was almost right, actually.

    0 讨论(0)
提交回复
热议问题