In my Jodd library I have a method that loads a class from given class name. Since this method has to be fail-safe (and smart;), i coded several ways for loading a class in following order:
using current thread classloader:
Thread.currentThread().getContextClassLoader().loadClass(className);
if above fails, than
forName
is used:Class.forName(className);
if above fails, then classloader of util class is used:
ClassLoaderUtil.class.getClassLoader().loadClass(className);
and, if a an optional Class argument is given, its cl开发者_如何学Goassloader is used:
callingClass.getClassLoader().loadClass(className);
Do you think this is a good order and/or should some steps be removed/added? Thanx.
Usually, you just provide a method where the caller provides the ClassLoader
directly - that would eliminate 1) and 4) (e.g. TCCL and callingClass.getClassLoader()).
Most libraries dealing with dynamic class loading provide two methods, one where the default lookup strategy is used as you describe it, and one where only the given ClassLoader is used.
Keep in mind that there may be expensive ClassLoaders, so every trial-and-error call of these loadClass() methods may trigger e.g. remote connections (for example in Applets) or even database lookups (yes, i've seen that too). In such cases, it's great to have a way to inject my own ClassLoader instance, e.g. for caching or blacklisting resources.
The order in which your default strategy works seems good to me. The most important one being definitely the TCCL, since this is the best approach when running in containers.
精彩评论