2010-05-25 74 views
0

我需要扫描实现或扩展特定类的类或jar文件。
这与Eclipse用来扫描插件的机制是一样的。 有一种方法可以做到这一点?Java中的扫描类或jar文件

+0

有办法,但你不应该需要它;) – Bozho 2010-05-25 08:34:50

+1

@Bozho:为什么不呢?别告诉我你可以闻到它;)。 – 2010-05-25 08:38:02

回答

1

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()

+0

如果我会从jar中加载它? – enfix 2010-05-25 10:43:04

+0

已更新的答案。 – aioobe 2010-05-25 10:51:25

0

是的,有方法可以做到这一点。看看文档here

更具体环节,

+0

我如何加载这个特定的类? 我扫描它,但然后我还需要加载它,只有当它实现了一个特定的接口。 – enfix 2010-05-25 08:41:37

+0

@enfix:首先你加载它然后你扫描它,如果它符合你的要求使用它,否则扔它。 – 2010-05-25 10:08:36

0

您可以通过使用字节码解析器(如ASM或BCEL)对其进行扫描而无需进行类加载。随着ASM ...

byte[] bytecode = [read bytes from class or jar file]; 
ClassReader reader = new ClassReader(bytecode); 
String[] interfaces = reader.getInterfaces();