【问题标题】:Load Java-Byte-Code at Runtime在运行时加载 Java 字节码
【发布时间】:2010-07-04 11:06:39
【问题描述】:

我得到了一些在我的程序中生成的 java-byte-code(如此编译的 java-source)。现在我想把这个字节码加载到当前运行的 Java-VM 中并运行一个特定的函数。我不确定如何实现这一点,我对 Java 类加载器进行了一些研究,但没有找到直接的方法。

我找到了一个解决方案,它在硬盘上获取一个类文件,但是我得到的字节码是一个字节数组,我不想把它写到磁盘上,而是直接使用它。

谢谢!

【问题讨论】:

  • 我认为在这个链接下你应该找到你要找的东西:tutorials.jenkov.com/java-reflection/… 看最后一节“ClassLoader Load / Reload Example”。
  • 我的问题有点不清楚:我没有类文件,但有一个字节数组,我想直接加载它。还是谢谢!
  • 我很确定我的链接提供的正是这一点。至少我通过它找到了这个:java.sun.com/j2se/1.4.2/docs/api/java/lang/…, int, int) 而且你显然总是可以将你的字节数组保存到一个临时目录中。

标签: java classloader bytecode


【解决方案1】:

你需要编写一个自定义类加载器来重载 findClass 方法

public Class findClass(String name) {
    byte[] b = ... // get the bytes from wherever they are generated
    return defineClass(name, b, 0, b.length);
}

【讨论】:

  • 谢谢,听起来是个办法,但是不写自定义类加载器就没有直接的办法吗?
  • 至少到目前为止我还没有找到
【解决方案2】:

如果字节码不在运行程序的类路径中,可以使用 URLClassLoader。来自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) {
}

【讨论】:

  • 我的问题有点不清楚:我没有类文件,但有一个字节数组,我想直接加载它。还是谢谢!
  • 随时编辑您的问题以更准确。引用的代码适用于硬盘上的类文件。
猜你喜欢
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
相关资源
最近更新 更多