Re: Generics and ClassLoaders
- From: "John C. Bollinger" <jobollin@xxxxxxxxxxx>
- Date: Fri, 29 Apr 2005 09:37:12 -0500
Josef Garvi wrote:
Assuming: String myClass = "some.package.SomeClass"; ClassLoader aClassLoader = someClassLoader;
This statement provokes a type-safety warning when using c.newInstance(): Class c = aClassLoader.loadClass(myClass);
This statement gives an error: Class<LinkHandler> c = aClassLoader.loadClass(myClass);
This statement gives a warning: Class<LinkHandler> c = (Class<LinkHandler>) aClassLoader.loadClass(myClass);
How should I load the class if I want to avoid the error message? Or has this become a "don't" in Java 5.0?
Look at the Javadocs: ClassLoader.loadClass(String) returns a Class<?>. You can assign it to a variable of that type without warning. This makes complete sense, because there is no general way to determine at compile time what type the method will load a Class for. The class might not even be available to the compiler. Making any assumption about what class has been loaded is inherently a type safety problem (which is nothing new; it's just that Java 5 produces warnings for it, and previous compilers didn't). You should load the class per your last example, and put up with the type safety warning that you will get.
-- John Bollinger jobollin@xxxxxxxxxxx
.
- Follow-Ups:
- Re: Generics and ClassLoaders
- From: Josef Garvi
- Re: Generics and ClassLoaders
- References:
- Generics and ClassLoaders
- From: Josef Garvi
- Generics and ClassLoaders
- Prev by Date: HTML Parser - problem with multiple instances
- Next by Date: IMPOSSIBLE to do this with LOG4J
- Previous by thread: Generics and ClassLoaders
- Next by thread: Re: Generics and ClassLoaders
- Index(es):
Relevant Pages
|
|