在某些情况下,您可能需要加载一些不在类路径中的类。
Java示例
假设文件夹“ c:\\ other_classes \\ ”不在您的项目类路径中,这是一个示例,说明如何从该文件夹加载Java类。 代码和注释是不言自明的。
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.ProtectionDomain;
public class App{
public static void main(String[] args) {
try{
File file = new File("c:\\other_classes\\");
//convert the file to URL format
URL url = file.toURI().toURL();
URL[] urls = new URL[]{url};
//load this folder into Class loader
ClassLoader cl = new URLClassLoader(urls);
//load the Address class in 'c:\\other_classes\\'
Class cls = cl.loadClass("com.mkyong.io.Address");
//print the location from where this class was loaded
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL urlfrom = cSource.getLocation();
System.out.println(urlfrom.getFile());
}catch(Exception ex){
ex.printStackTrace();
}
}
}
输出量
/c:/other_classes/
您会注意到该类是从“ / c:/ other_classes / ”加载的,该类不在您的项目类路径中。
翻译自: https://mkyong.com/java/how-to-load-classes-which-are-not-in-your-classpath/