Search code examples
javaclassloaderbytecode

Load Java-Byte-Code at Runtime


I got some java-byte-code (so compiled java-source) which is generated in my program. Now I want to load this byte-code into the currently running Java-VM and run a specific function. I'm not sure how to accomplish this, I digged a little bit into the Java Classloaders but found no straight way.

I found a solution which takes a class-file on the harddisk, but the bytecode I got is in a Byte-Array and I dont want to write it down to the disk but use it directly instead.

Thanks!


Solution

  • you need to write a custom class loader that overloads the findClass method

    public Class findClass(String name) {
        byte[] b = ... // get the bytes from wherever they are generated
        return defineClass(name, b, 0, b.length);
    }