Method to dynamically load java class files

試著忘記壹切 提交于 2019-11-26 05:22:17

问题


What would be a good way to dynamically load java class files so that a program compiled into a jar can read all the class files in a directory and use them, and how can one write the files so that they have the necessary package name in relation to the jar?


回答1:


I believe it's a ClassLoader you're after.

I suggest you start by looking at the example below which loads class files that are not on the class path.

// 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) {
}



回答2:


MyClass obj = (MyClass) ClassLoader.getSystemClassLoader().loadClass("test.MyClass").newInstance();
obj.testmethod();

or

MyClass obj = (MyClass) Class.forName("test.MyClass").newInstance();
obj.testmethod();



回答3:


If you add a directory to your class path, you can add classes after the application starts and those classes can be loaded as soon as they have been written to the directory.



来源:https://stackoverflow.com/questions/6219829/method-to-dynamically-load-java-class-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!