动态加载java类文件的方法

Mir*_*ate 42 java reflection load class dynamic

什么是动态加载java类文件的好方法,以便编译到jar中的程序可以读取目录中的所有类文件并使用它们,以及如何编写文件以便它们具有相关的必要包名到罐子里?

aio*_*obe 89

我相信这是ClassLoader你的追求.

我建议你先看看下面的例子,它加载不在类路径上的类文件.

// 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.toURI().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) {
}
Run Code Online (Sandbox Code Playgroud)


d2k*_*2k2 8

MyClass obj = (MyClass) ClassLoader.getSystemClassLoader().loadClass("test.MyClass").newInstance();
obj.testmethod();
Run Code Online (Sandbox Code Playgroud)

要么

MyClass obj = (MyClass) Class.forName("test.MyClass").newInstance();
obj.testmethod();
Run Code Online (Sandbox Code Playgroud)