Loading Java bytecode at runtime

I got some java bytecode (so compiled java-source) which is generated in my program. Now I want to load this bytecode into the currently running Java-VM and run a specific function. I'm not sure how to do this, I worked a bit in Java Classloaders, but did not find a direct path.

I found a solution that takes the class file on the hard drive, but the bytecode I received is in a byte array, and I don't want to write it to disk, but use it directly.

Thanks!

+7
java bytecode classloader
source share
2 answers

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); } 
+9
source share

If the bytecode is not in the classpath of the running program, you can use URLClassLoader. From http://www.exampledepot.com/egs/java.lang/LoadClass.html

 // Create a File object on the root of the directory containing the class file File file = new File("c:\\myclasses\\"); try { // Convert File to a URL URL url = file.toURL(); // file:/c:/myclasses/ URL[] urls = new URL[]{url}; // Create a new class loader with the directory ClassLoader cl = new URLClassLoader(urls); // Load in the class; MyClass.class should be located in // the directory file:/c:/myclasses/com/mycompany Class cls = cl.loadClass("com.mycompany.MyClass"); } catch (MalformedURLException e) { } catch (ClassNotFoundException e) { } 
+2
source share

All Articles