动态加载Java类文件的方法

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

MirroredFate asked 2020-08-05T12:04:12Z
3个解决方案
88 votes

我相信这是您追求的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) {
}
aioobe answered 2020-08-05T12:04:42Z
8 votes
MyClass obj = (MyClass) ClassLoader.getSystemClassLoader().loadClass("test.MyClass").newInstance();
obj.testmethod();

要么

MyClass obj = (MyClass) Class.forName("test.MyClass").newInstance();
obj.testmethod();
d2k2 answered 2020-08-05T12:05:02Z
1 votes

如果将目录添加到类路径,则可以在应用程序启动后添加类,并且可以在将这些类写入目录后立即加载它们。

Peter Lawrey answered 2020-08-05T12:05:22Z
translate from https://stackoverflow.com:/questions/6219829/method-to-dynamically-load-java-class-files