title: Marking one method as preferred to automatically resolve ambiguous calls?
body: <p>Let's say I define myself a new type of byte stream (similar to OutputStream):</p>
  
  <pre><code>public interface MyByteStream {
      public void write(byte[] data) throws IOException;
  }
  </code></pre>
  
  <p>Also, I have a helper class that can write Strings to a byte stream, and for flexibility, I would like to have two versions of its method, so that it works with either a regular OutputStream or my new MyByteStream:</p>
  
  <pre><code>public class StringWriter {
      public void write(String string, MyByteStream stream) throws IOException {
          stream.write(string.getBytes());
      }
  
      public void write(String string, OutputStream stream) throws IOException {
          stream.write(string.getBytes());
      }
  }
  </code></pre>
  
  <p>Now, if I have a class that extends OutputStream <strong>and</strong> implements MyByteStream, like this:</p>
  
  <pre><code>public class DebugStream extends OutputStream implements MyByteStream {
      @Override
      public void write(int b) throws IOException {
          System.out.println(b);
      }
  }
  </code></pre>
  
  <p>I can't just call my StringWriter's write method like this:</p>
  
  <pre><code>new StringWriter().write("Hello", new DebugStream());
  </code></pre>
  
  <p>as it will give me the following error:</p>
  
  <pre class="lang-none prettyprint-override"><code>The method write(String, MyByteStream) is ambiguous for the type StringWriter
  </code></pre>
  
  <p>I can resolve the problem by explicitly casting the DebugStream to one of the byte streams, like so:</p>
  
  <pre><code>new StringWriter().write("Hello", (OutputStream) new DebugStream());
  new StringWriter().write("Hello", (MyByteStream) new DebugStream());
  </code></pre>
  
  <p>But since the two methods do the exact same thing anyways, I would much rather not have to do the cast everywhere. Is there some way around this? Like defining one of the methods as preferred for such ambiguous calls? Or maybe some generics-trickery?</p>
  
  <p>Note:</p>
  
  <p>I would like to keep compile-time type-safety alive, so "solutions" along the following lines are out:</p>
  
  <pre><code>public class StringWriter {
      public void write(String string, Object stream) throws IOException {
          if (stream instanceof OutputStream) {
              ((OutputStream) stream).write(string.getBytes());
          } else if (stream instanceof MyByteStream) {
              ((MyByteStream) stream).write(string.getBytes());
          } else {
              throw new IllegalArgumentException();
          }
      }
  }
  </code></pre>