Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

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

It's legal to do this in Java:

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

How can I do this (syntax not legal):

 void spew(Appendable & Closeable x)
 {
     x.append("Bleah!
");
     if (timeToClose())
         x.close();
 }

I would like if possible to force callers to use objects that are both Appendable and Closeable, without requiring a specific type. There are multiple standard classes that do this, e.g. BufferedWriter, PrintStream, etc.

If I define my own interface

 interface AppendableAndCloseable extends Appendable, Closeable {}

that won't work since the standard classes that implement Appendable and Closeable do not implement my interface AppendableAndCloseable (unless I don't understand Java as well as I think I do... empty interfaces still add uniqueness above and beyond their superinterfaces).

The closest I can think of is to do one of the following:

  1. pick one interface (e.g. Appendable), and use runtime tests to ensure the argument is an instanceof the others. Downside: problem not caught at compile time.

  2. require multiple arguments (catches compile-time correctness but looks dorky):

    void spew(Appendable xAppend, Closeable xClose)
    {
        xAppend.append("Bleah!
    ");
        if (timeToClose())
            xClose.close();
    }
    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do it with generics:

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

Your syntax was almost right, actually.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...