以下 Java 7 代码将列出-XX:+PrintFlagsFinal
. 它尝试使用反射来访问受包保护的帮助程序类(自 Java 6 起可用),如果不起作用则Flag
回退。HotSpotDiagnosticMXBean.getDiagnosticOptions()
// load the diagnostic bean first to avoid UnsatisfiedLinkError
final HotSpotDiagnosticMXBean hsdiag = ManagementFactory
.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
List<VMOption> options;
try {
final Class<?> flagClass = Class.forName("sun.management.Flag");
final Method getAllFlagsMethod = flagClass.getDeclaredMethod("getAllFlags");
final Method getVMOptionMethod = flagClass.getDeclaredMethod("getVMOption");
getAllFlagsMethod.setAccessible(true);
getVMOptionMethod.setAccessible(true);
final Object result = getAllFlagsMethod.invoke(null);
final List<?> flags = (List<?>) result;
options = new ArrayList<VMOption>(flags.size());
for (final Object flag : flags) {
options.add((VMOption) getVMOptionMethod.invoke(flag));
}
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException
| InvocationTargetException | ClassCastException e) {
if (hsdiag != null) {
// only includes writable external flags
options = hsdiag.getDiagnosticOptions();
} else {
options = Collections.emptyList();
}
}
final Map<String, VMOption> optionMap = new TreeMap<>();
for (final VMOption option : options) {
optionMap.put(option.getName(), option);
}
for (final VMOption option : optionMap.values()) {
System.out.println(option.getName() + " = " + option.getValue() + " (" +
option.getOrigin() + ", " +
(option.isWriteable() ? "read-write" : "read-only") + ")");
}
System.out.println(options.size() + " options found");
使用 7u71,我得到 663 个选项,或者使用-XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions
, 779。