通过非反射方法获取总物理内存

This commit is contained in:
yushijinhun 2018-05-27 11:04:39 +08:00
parent 663e1ef7ab
commit 6c0d6ee0cf
No known key found for this signature in database
GPG Key ID: 5BC167F73EA558E4

View File

@ -24,6 +24,11 @@ import java.io.File;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.Locale; import java.util.Locale;
import java.util.Optional;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
/** /**
* Represents the operating system. * Represents the operating system.
@ -103,11 +108,9 @@ public enum OperatingSystem {
else else
CURRENT_OS = UNKNOWN; CURRENT_OS = UNKNOWN;
Object bytes = ReflectionHelper.call(ManagementFactory.getOperatingSystemMXBean(), "getTotalPhysicalMemorySize"); TOTAL_MEMORY = getTotalPhysicalMemorySize()
if (bytes instanceof Long) .map(bytes -> (int) (bytes / 1024 / 1024))
TOTAL_MEMORY = (int) (((Long) bytes) / 1024 / 1024); .orElse(1024);
else
TOTAL_MEMORY = 1024;
SUGGESTED_MEMORY = (int) (Math.round(1.0 * TOTAL_MEMORY / 4.0 / 128.0) * 128); SUGGESTED_MEMORY = (int) (Math.round(1.0 * TOTAL_MEMORY / 4.0 / 128.0) * 128);
@ -117,6 +120,19 @@ public enum OperatingSystem {
SYSTEM_ARCHITECTURE = arch; SYSTEM_ARCHITECTURE = arch;
} }
private static Optional<Long> getTotalPhysicalMemorySize() {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
try {
Object attribute = mBeanServer.getAttribute(new ObjectName("java.lang", "type", "OperatingSystem"), "TotalPhysicalMemorySize");
if (attribute instanceof Long) {
return Optional.of((Long) attribute);
}
} catch (JMException e) {
return Optional.empty();
}
return Optional.empty();
}
public static void setClipboard(String string) { public static void setClipboard(String string) {
ClipboardContent c = new ClipboardContent(); ClipboardContent c = new ClipboardContent();
c.putString(string); c.putString(string);