How can I dynamically load classes within an MBean?
So you have created your cool MBean service and you want to dynamically
load and instantiate a class, to implement some sort of plug-in mechanism.
The typical mistake is to use:
This won't work correctly because the bootstrap class loader will be used
to load that class, and this is almost always wrong unless you want to
load system classes.
JBoss uses an advanced and fully configurable classloading mechanism that
associates a UnifiedClassLoader with each top-level deployment. The trick
here is to load the class using the classloader associated with the
deployment, so that you integrate with the JBoss classloading model.
To do this you can do:
// get the classloader associated with the thread ClassLoader cl = Thread.currentThread().getContextClassLoader(); // load the class Class clazz = cl.loadClass("somepackage.SomeClass"); // do whatever with it SomeClass someClass = (SomeClass)clazz.newInstance(); ...