Reputation: 31212
I am trying to write a simple code analyzer and, for starters, just want to create an instance of a ClassLoader
whose classpath is a single jar file, independent of the classpath of the actual code analyzer application. Then I want to get a listing of all the entries within but then use reflection on each one within the context of the classpath to do some basic code analysis and tabulate the results.
Is it possible to create a ClassLoader that contains a single jar whose listings can be further analyzed using reflection?
For example, create a custom loader:
String clspath = "/my/dir/myjar.jar";
URL clspathURL = null;
try {
clspathURL = new URL("file:///" + clspath);
} catch(MalformedURLException badURLex) {
}
Then do something to list all the classes it loaded OR (not sure if it loads all the classes available to it upon initialization) if it does not load all the classes, load them
Then be able to do an in memory code analysis using reflection.
Upvotes: 0
Views: 275
Reputation: 5978
Getting a list of the files from a jar and loading the class for reflection are two separate things. Use a ZipInputStream
for the first and a URLClassLoader
for the second task:
URL jar = ...;
ClassLoader cl = new URLClassLoader(new URL[]{jar});
ZipInputStream zip = new ZipInputStream(jar.openStream());
while(true) {
ZipEntry e = zip.getNextEntry();
if (e == null)
break;
String nameAsInZip = e.getName():
if(nameAsInZip.endsWith(".class")) {
String nameForClassLoader = ....; // transform name for CL
Class clazz = cl.loadClass(nameForClassLoader);
// analyze class
}
}
Upvotes: 1