dcsimg
 

Submitted by: Octavia Anghel(octaviaanghel@gmail.com)

Wednesday Jul 25th 2018 by Octavia Anghel

Language: Java, Expertise: Intermediate - See how to avoid using the wrong class loader.

This code uses the class loader that loads the current class and getClass() could return something unexpected, like a subclass, or a dynamic proxy. This is hardly ever what you want when you dynamically load an additional class, moreover in managed environments such as Servlet Engines or Java Webstart, application servers this is most certainly wrong.

Class myclass = Class.forName(name);
Class myclass = getClass().getClassLoader().loadClass(name);

This code will comport very differently depending on the environment in which it runs. Environments that use the context class loader to provide applications with a class loader should use it to retrieve their own classes.

ClassLoader cl = Thread.currentThread().getContextClassLoader();
If (cl == null)  cl = MyClass.class.getClassLoader(); 
Class myclass =  cl.loadClass(name);
Home
Mobile Site | Full Site