Re: Generics and ClassLoaders



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

.



Relevant Pages

  • Re: What is warning: [unchecked] ?
    ... Post the results of command-line commad: java ... using to compile the class. ... I don't see that warning on my system: ... www.EdmundKirwan.com - Home of The Fractal Class Composition. ...
    (comp.lang.java.help)
  • Re: What is warning: [unchecked] ?
    ... >> warning: ... Post the results of command-line commad: java ... i> using to compile the class. ... jdh punt beekhuizen bij duinheks punt xs4all punt nl ...
    (comp.lang.java.help)
  • Re: how to solve this warning in Eclipse?
    ... The basic idea of generics is to introduce several features that encourage type safety in your code. ... Basically, to stop your warnings, you need to tell Java what sort of Object you are going to store in your Vectors. ... No matter what I do I can't get the warning to go away. ...
    (comp.lang.java.programmer)
  • Re: Creating a Generic array
    ... > As far as I know, you can't get a generic array ... > implementation of a stack to compile without ... > a warning. ... > or in the way arrays are implemented in Java, ...
    (comp.lang.java.programmer)
  • (Help Me!) Problem in Compiling Nx Src on FreeBSD Machine of version 5.2.1-RELEASE FreeBSD 5.2.1-REL
    ... checking for gcc... ... Compile FreeType first. ... ttcmap.h:124: error: syntax error before "Bool" ... ttapi.c:124: warning: dereferencing type-punned pointer will break ...
    (freebsd-arch)