使用Java Reflection从类路径之外加载类 [英] loading a class from out of classpath by using Java Reflection
本文介绍了使用Java Reflection从类路径之外加载类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要从不在类路径中的类中加载类。
有什么方法可以按文件路径加载类而不在类路径中?例如
I want to load class from that is not in class path. is there any way that I load class by file path without being in classpath ? for example
ClassLoader.load("c:\MyClass.class");
推荐答案
示例取自此处:
// 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) {
}
这篇关于使用Java Reflection从类路径之外加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文