9

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!

3
  • I think under this link you should find what you are looking for: tutorials.jenkov.com/java-reflection/… Look at the last section "ClassLoader Load / Reload Example". Commented Jul 4, 2010 at 11:23
  • My question was somehow unclear: I haven't got a class-file but a byte-array and I want to load it directly. Thanks anyway! Commented Jul 4, 2010 at 13:04
  • And I'm pretty sure my link provided exactly that. At least I found this through it: java.sun.com/j2se/1.4.2/docs/api/java/lang/…, int, int) Also you can obviously always save your byte-array to a temporary directory. Commented Jul 4, 2010 at 15:06

2 Answers 2

11

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, sounds like a way to got, but there is no direct way without writing a custon ClassLoader?
at least none i have found so far
2

If the byte code is not on 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 Comments

My question was somehow unclear: I haven't got a class-file but a byte-array and I want to load it directly. Thanks anyway!
Feel free to edit your question to be more precise. The code quoted works with class files ón the harddisk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.