可以通過使用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文檔。