How can I load java class from database?

If you want to store the source code in you DB, you can use the Java 6 Compiler API to compile it at runtime. See here for an example.

In order to load classes at runtime, you can either use an URLClassLoader if you can specify the location of the bytecode with a URL, or use ClassLoader.defineClass and supply the bytecode as an array of bytes.

Either way you should pay attention, that in order to use your dynamically loaded class, it should implement an interface that is known at compile time.


Assuming you already compiled the class, you can create a DatabaseClassLoader, which loads the class from a database.

public class DatabaseClassLoader extends ClassLoader {

    public DatabaseClassLoader(ClassLoader parent, ... /* connection to database */ ) {
       super(parent);
       // store the connection
    }

    public Class findClass(String name) {
       byte[] data = loadDataFromDatabase(name);
       return defineClass(name, data, 0, data.length);
    }
    private byte[] loadDataFromDatabase(String name) {
        // this is your job.
    }
}

If the database only contains the source code, you'll have to compile it first - look into the Java compiler API for how to do this without any files.

Pay attention, the class loaded this way will stay alive as long as the classloader is alive, so you'll need a new class loader to be able to reload the class in case of changes.

Also, if you want to interact with the class by other ways than reflection, you would better let it implement some interface (which itself is in your class path), and let the application class loader be the parent of your database class loader.

Ah, and how to load:

Class<?> c = Class.forName("util.abc.Test", myClassLoader);

or directly

Class<?> c = myClassLoader.loadClass("util.abc.Test");

Here is a method which creates objects of your interface (of any interface, in fact):

public <X> X getImplementingObject(Class<X> interfaceClass, String className)
   throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
    ClassLoader loader = new DatabaseClassLoader(interfaceClass.getClassLoader(), ...);
    Class<?> cl = loader.loadClass(className);
    Class<? extends X> c = cl.asSubclass(interfaceClass);
    return c.newInstance();
}

(It needs the class to have a no-argument constructor which does not throw any exceptions, of course (if it does, you'll get this exception thrown, too).

This creates a new ClassLoader for every such class, so they can only cooperate with each other by means of the interface (or reflection).

For on-the-fly compiling you should look at the Java Compiler API, as mentioned in the answer from dcn. But I think it would be better to do the compiling on the side which puts the classes into the database than the side who pulls them out.

Tags:

Java