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.
There is a way to do this ?
Asked
Active
Viewed 4,153 times
0

enfix
- 6,680
- 12
- 55
- 80
-
there are ways, but you shouldn't need it ;) – Bozho May 25 '10 at 08:34
-
1@Bozho: Why not? Don't tell me you can smell it ;). – Adeel Ansari May 25 '10 at 08:38
3 Answers
1
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()
.
0
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();

Jeff Williams
- 921
- 7
- 9
0
Yes, there are methods just to do that. Look at the docs here.
More specific links,

Adeel Ansari
- 39,541
- 12
- 93
- 133
-
How can i load this specific class ? I scan it but then i need also to load this only if it implements a specific interface. – enfix May 25 '10 at 08:41
-
@enfix: First you load it then you scan it, if it comply with your requirement use it, otherwise throw it. – Adeel Ansari May 25 '10 at 10:08