Other |
---|
5.0 b32Fixed |
Duplicate :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
Date: Fri, 13 Jun 2003 23:37:54 +0400 From: Roman Elizarov <###@###.###> Subject: JSR14 prototype comments - Class<T> goodies and shortcomings To: ###@###.### Reply-to: Roman Elizarov <###@###.###> Hello! In short - I'm glad to see variance on board, but there are some concerns. It's nice to be able to cleanly express the following method signatures that happen this or other way all over various libraries in J2SE and J2EE, like: javax.rmi.PortableRemoteObject: public static <T> narrow(Object o, Class<T> c); javax.security.auth.Subject: public Set<T> getPublicCredentials(Class<T> c); etc ... Being declared this way they are much easier to use. Benefits are immense especially in J2EE (happens all the time). Instead of writing: MyHome h = (MyHome)narrow(..., MyHome.class); one is now able to simply write: MyHome h = narrow(..., MyHome.class); And it works! But, here's the problem - the following naive implementation: static <T> narrow(Object o, Class<T> c) { return (T)o; } Compiles with "unchecked cast to type T" warning. Moreover, I don't see how one can implement methods with those signatures without triggering this warning. It looks like a significant shortcoming in the type system. Class<T> construct should actually hint the compiler that T is a non-generic class type (there's no such thing like Class<Set<String>>, but only Class<Set>), and thus cast conversion to T shall be allowed in this context without "unsafe" warning. Of course, it may still produce ClassCastException, but it is perfectly safe. If you decide to follow this path, consider also the fact that in the above context it is also possible to compile expression like "o instanceof T", which is not valid in the absence of Class<T> c. Sincerely, Roman Elizarov
|