> -----Original Message-----
> From: Jonathan Hawkes [mailto:[EMAIL PROTECTED]
> Sent: den 28 januari 2004 20:08
> To: Avalon Developers List
> Subject: Re: Java 1.5, fun with lookups and generics
>
>
> > OK, *that* is something that can't be statically checked.
> The upside
> > is that we've isolated the *only* part that can't be statically
> > checked, and we've isolated it in the container:
> >
> > try {
> > return (T) o; // unchecked cast to type T
> here, should
> > be fine.
> > } catch (Throwable t) {
> > return null;
> > }
> >
> > /LS
>
> So, in the container code, we could have something like this:
>
> if (o instanceof T) {
> return o;
> } else {
> throw new StupidAvalonProgrammerException(); // instead
> of ClassCastException }
Something like that - except you can't do that.
The type parameter T gets "erased" so *at runtime*, T = Object.
This makes your test:
if (o instanceof Object) {
return o;
} else {
throw new StupidAvalonProgrammerException();
}
What you have to do is:
public <T> T lookup (Class<T> expectedClass, String key) throws
Exception {
Object o = doGet (key);
if (expectedClass.isAssignableFrom (o.getClass ())) {
return (T) o; // unchecked cast to type T here, should be
fine.
} else {
throw new StupidAvalonProgrammerException();
}
}
And use it client-side like this:
MyComponent comp = sm.lookup (MyComponent.class, "MyComponent");
You can also use a helper method for the cases when
key == expectedClass.getName ():
public <T> T lookup (Class<T> expectedClass) throws Exception {
return lookup (expectedClass, expectedClass.getName ());
}
And write:
MyComponent comp = sm.lookup (MyComponent.class);
(Everyone confused yet, or shall I have another go at it?)
/LS
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]