Question

Is there a way to compile and load a Java class during runtime without creating and storing a file in an operating system filesystem?

Say I have a database record that contains the string representation of a java class. I pull that string into Java memory. My goal is to compile that String into a java class and then load that class.

Let me make this clear. I want nothing to do with .java files or .class files, in any operating system.

Is this possible? And how?

For instance, here is code to load a Groovy class at runtime, and invoke a method:

ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(new File("src/test/groovy/script/HelloWorld.groovy"));

// let's call some method on an instance
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
Object[] args = {};
groovyObject.invokeMethod("run", args);

but could we do something like:

    ClassLoader parent = getClass().getClassLoader();
    GroovyClassLoader loader = new GroovyClassLoader(parent);
    Class groovyClass = loader.parseClass(new String("public class GroovyClass{}"));

?

Was it helpful?

Solution

Yes, I have a library which does this called OpenHFT/Java-Runtime-Compiler which replaces essence jcf. There is also other librarires such as beanshell and groovy which support this, but I haven't used them myself.

OTHER TIPS

If you can store the bytecode you should be able to do something like what is shown in the Javadoc for ClassLoader. You simply override the findClass(String) method.

public MyClassLoader extends ClassLoader {

    public Class findClass(String name) {
        byte[] b = fetchClassFromDB(String name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] fetchClassFromDB(String name) {
         /* Look up class in your database and return it as a byte array. */
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top