How to require a parameter be of two types when passed to a method in Java
<p>In one class, I have to call a constructor of another class that needs two parameters, a <code>IHelloServiceConnectionObserver</code> and a <code>ContextWrapper</code>. The problem is they're both <code>this</code>.</p>

<p>Note: <code>ContextWrapper</code> is a framework class that I have no control over (<code>android.content.ContextWrapper</code>, actually). My class (an Android <code>Activity</code>) is-a <code>ContextWrapper</code> already, and I want to mix-in a little <code>IHelloServiceConnectionObserver</code>ness to it.</p>

<p>Also note, my class is one of several classes that all inherit from <code>ContextWrapper</code>, so combining <code>ContextWrapper</code> and <code>IHelloServiceConnectionObserer</code> won't work.</p>

<p>I could do this:</p>

<pre><code>HelloServiceConnection svc = HelloServiceConnection(this,this);
</code></pre>

<p>calls</p>

<pre><code>public HelloServiceConnection(IHelloServiceConnectionObserver observer, ContextWrapper contextWrapper){
    this.observer = observer;
    this.contextWrapper = contextWrapper;
}
</code></pre>

<p>But that looks silly. Or I could do this:</p>

<pre><code>HelloServiceConnection svc = HelloServiceConnection(this);
</code></pre>

<p>calls</p>

<pre><code>public HelloServiceConnection(IHelloServiceConnectionObserver observer){
    this.observer = observer;
    this.contextWrapper = (ContextWrapper) observer;
}
</code></pre>

<p>But now I move a nice compile time error to a runtime error.</p>

<p>What's the best practice here?</p>

<p>EDIT: Well, I can't say it's a "best practice", but for my special set of circumstances, Jon Skeet has the right answer.  Here's what the code ends up looking like:</p>

<pre><code>helloServiceConnection = HelloServiceConnection.create(this);
</code></pre>

<p>calls</p>

<pre><code>public static &lt;T extends ContextWrapper &amp; IHelloServiceConnectionObserver&gt; HelloServiceConnection create(T value){
    return new HelloServiceConnection(value, value);
}
</code></pre>

<p>which in turn calls</p>

<pre><code>private HelloServiceConnection(IHelloServiceConnectionObserver observer, ContextWrapper contextWrapper){
    this.observer = observer;
    this.contextWrapper = contextWrapper;
}
</code></pre>

<p>So let me give a bit more context as to why this is the right answer for this special situation.  Since <code>ContextWrapper</code> is part of a framework that I don't control, I can't change it. Because it's also an ancestor of several classes, any one of which I might want to use <code>HelloServiceConnection</code> in, it doesn't really make sense to extend all the decendants of <code>ContextWrapper</code> to add in <code>IHelloServiceConnectionObserver</code>.</p>

<p>So I thought I was left will little choice but the <code>this,this</code> idom. Jon's answer, once I understood it, saves the day!</p>

<p>Thanks, Jon -- and thanks to all who participated.</p>
