Merge pull request #9653 from anmoldeep0123/BAEL_4302
BAEL-4302 : How can I list all classes loaded in a specific class loader
This commit is contained in:
commit
a3ccd178e1
@ -0,0 +1,19 @@
|
||||
package com.baeldung.loadedclasslisting;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class Launcher {
|
||||
|
||||
public static void main(String[] args) {
|
||||
printClassesLoadedBy("BOOTSTRAP");
|
||||
printClassesLoadedBy("SYSTEM");
|
||||
printClassesLoadedBy("EXTENSION");
|
||||
}
|
||||
|
||||
private static void printClassesLoadedBy(String classLoaderType) {
|
||||
System.out.println(classLoaderType + " ClassLoader : ");
|
||||
Class<?>[] classes = ListLoadedClassesAgent.listLoadedClasses(classLoaderType);
|
||||
Arrays.asList(classes)
|
||||
.forEach(clazz -> System.out.println(clazz.getCanonicalName()));
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.loadedclasslisting;
|
||||
|
||||
import java.lang.instrument.Instrumentation;
|
||||
|
||||
public class ListLoadedClassesAgent {
|
||||
|
||||
private static Instrumentation instrumentation;
|
||||
|
||||
public static void premain(String agentArgs, Instrumentation instrumentation) {
|
||||
ListLoadedClassesAgent.instrumentation = instrumentation;
|
||||
}
|
||||
|
||||
public static Class<?>[] listLoadedClasses(String classLoaderType) {
|
||||
if (instrumentation == null) {
|
||||
throw new IllegalStateException(
|
||||
"ListLoadedClassesAgent is not initialized.");
|
||||
}
|
||||
return instrumentation.getInitiatedClasses(
|
||||
getClassLoader(classLoaderType));
|
||||
}
|
||||
|
||||
private static ClassLoader getClassLoader(String classLoaderType) {
|
||||
ClassLoader classLoader = null;
|
||||
switch (classLoaderType) {
|
||||
case "SYSTEM":
|
||||
classLoader = ClassLoader.getSystemClassLoader();
|
||||
break;
|
||||
case "EXTENSION":
|
||||
classLoader = ClassLoader.getSystemClassLoader().getParent();
|
||||
break;
|
||||
// passing a null value to the Instrumentation : getInitiatedClasses method
|
||||
// defaults to the bootstrap class loader
|
||||
case "BOOTSTRAP":
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return classLoader;
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
Premain-Class: com.baeldung.loadedclasslisting.ListLoadedClassesAgent
|
Loading…
x
Reference in New Issue
Block a user