Get total system memory and system components in java

-2

Is there a simple or reliable method to get the total memory of the computer and / or components or models of the computer components?

I searched a lot and the only thing I found was some articles talking about the class com.sun.management.OperatingSystemMXBean however it is "protected" and this generates an error in the IDEs and I do not know if it is safe to ignore this error, is giving some error is because something is wrong.

    
asked by anonymous 14.09.2018 / 05:21

1 answer

0

After giving a study I was able to develop a method that does not generate errors and works perfectly using Reflection and class OperatingSystemMXBean of java.lang

private long getFreeMemoryComputer() {
    try {
        OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
        Method getFreeMemory = system.getClass().getMethod("getFreePhysicalMemorySize");
        getFreeMemory.setAccessible(true);
        return (long) getFreeMemory.invoke(system);
    } catch (Exception e) {
        return -1;
    }
}

private long getTotalMemoryComputer() {
    try {
        OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
        Method getTotalMemory = system.getClass().getMethod("getTotalPhysicalMemorySize");
        getTotalMemory.setAccessible(true);
        return (long) getTotalMemory.invoke(system);
    } catch (Exception e) {
        return -1;
    }
}
    
14.09.2018 / 21:33