views:

54

answers:

1

Hi all,

I am trying to find a way to collected all java.lang.Class's loaded from jar files but ignore the ones from the source code itself.

I have found java.lang.instrument.Instrumentation interface and thought it might serve the purpose, but it turned out not quite.... One of the available functions "getAllLoadedClasses" dump all java.lang.Class's out (which is good), but it not only dump onces got loaded from jar file and also loaded from the source file.

Is there a configuration that allows us to customize the setting so only the java.lang.Class's originated from jar files are dumped or there is better solution in the wild?

What I want to achieve in code representation will be something like below.

java.lang.Class[]
classesLoadedFromJars = getClassesLoadedFromJars();

for (java.lang.Class class : classesLoadedFromJars) {
     // .............. 
}

A word or two on the suggestion will be helpful!

Thanks in advance.

A: 

The class's classloader should be able to give you a clue as to where a certain class was loaded from.

ClassLoader loader = myClass.getClassLoader()
if (loader instanceof URLClassLoader) {
    URLClassLoader uLoader = (URLClassLoader)loader;
    URL cURL = uLoader.getResource(myClass.getName().replace('.', '/')+".class");
}

if cURL starts with jar:// , the class originated from a jar file

mkadunc
what would be the function to use?
Daniel
added some example code. It seems there's no nicer way to do this than to get the classLoader to locate the .class file manually
mkadunc