Java中的扫描类或jar文件
从exmaple depot: How to load a Class that is not on the classpath:
// Create a File object on the root of the directory
// containing the class file
File file = new File("c:\\class\\");
try {
// Convert File to a URL
URL url = file.toURL(); // file:/c:/class/
URL[] urls = new URL[]{url};
// Create a new class loader with the directory
ClassLoader loader = new URLClassLoader(urls);
// Load in the class; Class.childclass should be located in
// the directory file:/c:/class/user/information
Class cls = loader.loadClass("user.informatin.Class");
} catch (MalformedURLException e) {
} catch (ClassNotFoundException e) {
}
列入目录中的文件,如果有必要,使用File.list()
。
加载类时,可以通过执行clazz.isInstance
来检查它是否实现了特定的接口。从文档:
确定指定的Object是否与此Class表示的对象分配兼容。这种方法是动态的相当于Java语言instanceof运算符。
从一个jar文件加载类:
How to load a jar file at runtime
要在jar文件中列出的文件:JarFile.entries()
。
我如何加载这个特定的类? 我扫描它,但然后我还需要加载它,只有当它实现了一个特定的接口。 – enfix 2010-05-25 08:41:37
@enfix:首先你加载它然后你扫描它,如果它符合你的要求使用它,否则扔它。 – 2010-05-25 10:08:36
您可以通过使用字节码解析器(如ASM或BCEL)对其进行扫描而无需进行类加载。随着ASM ...
byte[] bytecode = [read bytes from class or jar file];
ClassReader reader = new ClassReader(bytecode);
String[] interfaces = reader.getInterfaces();
有办法,但你不应该需要它;) – Bozho 2010-05-25 08:34:50
@Bozho:为什么不呢?别告诉我你可以闻到它;)。 – 2010-05-25 08:38:02