Load Java-Byte-Code at Runtime

放肆的年华 提交于 2019-11-30 09:18:06
Nikolaus Gradwohl

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);
}

If the byte code is not on the classpath of the running program, you can use URLClassLoader. From 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) {
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!