Java:在运行时从同一 JVM 中获取类的字节码 [英] Java: Getting Bytecode of Class at Runtime from within the Same JVM

查看:26
本文介绍了Java:在运行时从同一 JVM 中获取类的字节码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关:有没有办法在运行时获取类的字节码?

我正在为 Clojure 添加持久性,我终于可以添加函数了.在 Clojure 中,函数被字节编译成具有 invoke 方法(以及其他方法)的类.这样,功能是一流的.为了使这些持久化,我需要序列化和反序列化这些类.如何在无法访问 .class 文件的情况下获取类的字节码?

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?

如果我弄错了,请纠正我,但使用代理需要生成一个单独的虚拟机,代理连接到第一个虚拟机.我需要从同一个 VM 中执行此操作.

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.

仅使用 Serializable 来设置和获取 Class 对象是不够的.反序列化时,我需要加载类,并且在后续的 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.

推荐答案

您可以编写自己的 ClassLoader 并编写一个在类加载时记录字节码的方案.

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

您需要重写 findClass 来自己查找类文件,将其加载到内存中,将数据保存在某处(以便以后序列化),然后调用 defineClass 来定义JVM 中的那个类.

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.

这篇关于Java:在运行时从同一 JVM 中获取类的字节码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆