简体   繁体   中英

how can i get the name and package of all the classes loaded in the Java JVM

I'm trying to get a full list of all the classes loaded in the JVM including the classes loaded by the bootloader, platformclassloader and custom class loaders. Without using the Instrumentation API.

The methods exposed by the regular classLoaders return only the classes available in the package reference graph starting from the main function. So I'm unable to get the list of classes loaded dynamically at runtime, and also can't get classes loaded by the bootloader and platformclassloader.

I'm aware of the Instrumentation API but can't control the commandline arguements passed to the JVM so it's not an option for me.

I don't have any specific Java version constraints so I can take any solution on any 'live' version (lets say >=9)

Here is a solution specific to HotSpot JVM.
Works all JDK versions from 8 to 20.

The output is equivalent to what is printed by jmap -histo:all , but instead of printing to stdout, the result is returned as a String .

public static String getAllClassNames() throws JMException {
    return (String) ManagementFactory.getPlatformMBeanServer().invoke(
            new ObjectName("com.sun.management:type=DiagnosticCommand"),
            "gcClassHistogram",
            new Object[]{new String[]{"-all"}},
            new String[]{"[Ljava.lang.String;"});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM