All,
we all hate the:
MyComponent comp = (MyComponent) lookup (MyComponent.ROLE);
idiom. A typecast, and just too much typing to be fun.
I downloaded the JDK1.5 preview today, and wrote this:
interface ServiceManager {
public <T> T lookup (String key) throws Exception;
public void release (Object o);
}
class DefaultServiceManager implements ServiceManager {
public <T> T lookup (String key) throws Exception {
Object o = doGet (key);
try {
return (T) o; // unchecked cast to type T here, should
be fine.
} catch (Throwable t) {
return null;
}
}
private Object doGet (String key) {
if (key.equals ("A")) return new A();
if (key.equals ("B")) return new B();
return null;
}
public void release (Object o) {};
}
class A {}
class B {}
public class MyClass {
public static void main(String[] args) throws Exception {
ServiceManager sm = new DefaultServiceManager();
A a = sm.<A>lookup ("A");
B b = sm.<B>lookup ("B");
System.out.println (a);
System.out.println (b);
}
}
Resulting in:
[EMAIL PROTECTED]
[EMAIL PROTECTED]
Due to the type erasure mechanism used in 1.5, you can't select from a
type variable, but I understand that we're decoupling the lookup
key from the interface name anyway:
public <T> T lookup () throws Exception {
return (T) doLookup (T.ROLE); // T.ROLE is not a valid construct
}
/LS
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]