Search code examples
javaclojurepersistencebytecodejava-bytecode-asm

Java: Getting Bytecode of Class at Runtime from within the Same JVM


Related to: Is there a way to obtain the bytecode for a class at runtime?

I'm adding durability to Clojure, and I'm finally at the point where I'm ready to add functions. In Clojure, functions are byte compiled into classes with invoke methods (among others). In this way, functions are first class. To make these durable, I need to serialize and deserialize these classes. How do I get the bytecode for the class without having access to the .class file?

Please correct me if I'm mistaken, but using an agent requires spawning a separate VM with the agent connecting to the first VM. I need to do it from the same VM.

It's not enough to use Serializable to set and get the Class object. Upon deserializing, I need to load the class, and upon subsequent VM instances, there may be a class name collision. I need to modify the bytecode to rename the class to something unique at deserialization/class-load time.


Solution

  • You could write your own ClassLoader and hack up a scheme which records the bytecode as classes are loaded.

    You would need to override findClass to find the class file yourself, load it into memory, save the data somewhere (for later serialization), then call defineClass to define that class in the JVM.