从加载的类获取字节码 [英] Get bytecode from loaded class

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

问题描述

假设在我的JVM我有一个加载类类< C> myClass 。是否有可靠的 方法向JVM询问.class的字节码内容?也就是说像这样:

Suppose in my JVM I have a loaded class Class<C> myClass. Is there a reliable way to ask the JVM for the bytecode contents of the .class? I.e. something like this:

<C> byte[] getClassBytecode(Class<C> myClass) {
    return /* the contents of the .class resource where C was loaded from */;
}

(显然一个 InputStream 将与 byte [] )一样好。我知道我可以使用 myClass.getResource()(和朋友)来获取类文件,但是敲击类名,以获得一个URL,getResource感觉错了。另外,我不知道如何动态生成 C (例如使用 javax.tools.JavaCompiler )。

(obviously an InputStream would be as good as the byte[]). I know I can use myClass.getResource() (and friends) to fetch the class file, but hammering on the class name to get an URL to feed to getResource feels wrong. Also, I am not sure how this would behave in case C was dynamically generated (e.g. using javax.tools.JavaCompiler).

任何(更好的)想法?

注意:目标是能够推动< del> bytecode 类到不同的JVM并使用自定义类加载器加载它们。

note: the goal is to be able to push the bytecode classes to a different JVM and use a custom classloader to load them there

推荐答案


注意:目标是能够在不同的JVM上使用自定义类加载器加载字节码

note: the goal is to be able to load the bytecode using a custom classloader on a different JVM

类加载器不仅仅加载字节码。因此,如果能够从JVM内存中获取字节码(这在理论上是可能的,如果你写了很多实现特定的本地代码),它对你的远程类加载器是无用的。您需要给它一个实际的 .class 文件。

A classloader doesn't just load bytecode. Therefore, if you were able to get the bytecode out of the JVM memory (which is theoretically possible if you write a lot of implementation-specific native code), it would be useless to your remote classloader. You need to give it an actual .class file.

Class.getResource完成这项任务。因为它看起来和调用类在同一个包,所有你需要做的是获取类的简单名称,附加.class和你完成。

And Class.getResource() is the best way to accomplish this task. Since it looks in the same package as the invoking class, all you need to do is take the class' simple name, append ".class" and you're done.

如果你有内部或嵌套的类,它变得有点困难,但这是一个实现细节,你必须处理无论如何(如果你推初始类,你仍然需要拉任何依赖类)。

It does become a little more difficult if you have inner or nested classes, but that's an implementation detail that you'll have to deal with regardless (if you push the initial class, you'll still need to pull any dependent classes).

这篇关于从加载的类获取字节码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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