开发者

Scan class or jar file in Java

I need to scan class or jar file that implements or extend a specific class.

It's the same mechanism that Eclipse use to scan the plugin presence. Ther开发者_开发百科e is a way to do this ?


From 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) {
}

List the files in the directory if necessary, using File.list().

When the class is loaded, you can check if it implements a specific interface by doing clazz.isInstance. From the docs:

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator.


To load classes from a jar-file:

How to load a jar file at runtime

To list files in a jar file: JarFile.entries().


Yes, there are methods just to do that. Look at the docs here.

More specific links,

  • getGenericInterfaces()
  • getGenericSuperclass()


You can scan it without classloading it by using a bytecode parser such as ASM or BCEL. With ASM...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜