可以通过使用Java Management Extensions (JMX) API来获取JVM已加载的类名称。具体步骤如下:
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
public class JMXClient {
public static void main(String[] args) throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
// 连接成功后可以进行后续操作
}
}
import javax.management.ObjectName;
public class JMXClient {
public static void main(String[] args) throws Exception {
// 省略创建JMX连接的代码
ObjectName classLoadingMBean = new ObjectName("java.lang:type=ClassLoading");
int loadedClassCount = (int) mbsc.getAttribute(classLoadingMBean, "LoadedClassCount");
System.out.println("Loaded class count: " + loadedClassCount);
String[] loadedClassNames = (String[]) mbsc.getAttribute(classLoadingMBean, "LoadedClassNames");
for(String className : loadedClassNames) {
System.out.println(className);
}
jmxc.close();
}
}
通过以上代码,可以获取JVM已加载的类名称并输出到控制台。需要注意的是,需要启动JVM时开启JMX功能,具体方法可以参考JVM文档。