用Java扫描类或jar文件

时间:2010-05-25 08:29:07

标签: java

我需要扫描实现或扩展特定类的类或jar文件 它与Eclipse用于扫描插件存在的机制相同。 有办法做到这一点吗?

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

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

更具体的链接,

答案 2 :(得分:0)

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

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