In one class, I have to call a constructor of another class that needs two parameters, a IHelloServiceConnectionObserver
and a ContextWrapper
. The problem is they're both this
.
Note: ContextWrapper
is a framework class that I have no control over (android.content.ContextWrapper
, actually). My class (an Android Activity
) is-a ContextWrapper
already, and I want to mix-in a little IHelloServiceConnectionObserver
ness to it.
Also note, my class is one of several classes that all inherit from ContextWrapper
, so combining ContextWrapper
and IHelloServiceConnectionObserer
won't work.
I could do this:
HelloServiceConnection svc = HelloServiceConnection(this,this);
calls
public HelloServiceConnection(IHelloServiceConnectionObserver observer, ContextWrapper contextWrapper){
this.observer = observer;
this.contextWrapper = contextWrapper;
}
But that looks silly. Or I could do this:
HelloServiceConnection svc = HelloServiceConnection(this);
calls
public HelloServiceConnection(IHelloServiceConnectionObserver observer){
this.observer = observer;
this.contextWrapper = (ContextWrapper) observer;
}
But now I move a nice compile time error to a runtime error.
What's the best practice here?
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:
helloServiceConnection = HelloServiceConnection.create(this);
calls
public static <T extends ContextWrapper & IHelloServiceConnectionObserver> HelloServiceConnection create(T value){
return new HelloServiceConnection(value, value);
}
which in turn calls
private HelloServiceConnection(IHelloServiceConnectionObserver observer, ContextWrapper contextWrapper){
this.observer = observer;
this.contextWrapper = contextWrapper;
}
So let me give a bit more context as to why this is the right answer for this special situation. Since ContextWrapper
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 HelloServiceConnection
in, it doesn't really make sense to extend all the decendants of ContextWrapper
to add in IHelloServiceConnectionObserver
.
So I thought I was left will little choice but the this,this
idom. Jon's answer, once I understood it, saves the day!
Thanks, Jon -- and thanks to all who participated.