Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 928
theomega Avatar asked Jul 04 '10 11:07

theomega


People also ask

Can Java read byte code?

The Java command-line comes with the javap tool that displays information about the fields, constructors, and methods of a class file. Based on the options used, it can disassemble a class and show the instructions that comprise the Java bytecode.

How do I run bytecode?

Execution. A bytecode program may be executed by parsing and directly executing the instructions, one at a time. This kind of bytecode interpreter is very portable. Some systems, called dynamic translators, or just-in-time (JIT) compilers, translate bytecode into machine code as necessary at runtime.

Is bytecode a Java class loader?

The Java Virtual Machine's main job is to load class files and execute the bytecode they contain. There are multiple components of the Java Virtual Machine like class loader, the garbage collector (automatic memory management), interpreter, JIT compiler, thread management.

Which provides runtime environment for Java bytecode?

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.


1 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);
}
like image 195
Nikolaus Gradwohl Avatar answered Sep 18 '22 15:09

Nikolaus Gradwohl