Why is access restricted to jre6/lib/rt.jar for OperatingSystemMxBean?

后端 未结 4 932
陌清茗
陌清茗 2020-12-18 21:30

I\'m having a little trouble with some Java code I\'m trying to compile in Eclipse. I keep getting the following warning...

Access restriction: The type Ope         


        
相关标签:
4条回答
  • 2020-12-18 21:50

    Go to Window-->Preferences-->Java-->Compiler-->Error/Warnings. Select Deprecated and Restricted API. Change it to warning. Change forbidden and Discouraged Reference and change it to warning. (or as your need.)

    Thanks.

    0 讨论(0)
  • 2020-12-18 21:52

    Here it is explained Why Developers Should Not Write Programs That Call 'sun' Packages.

    A workaround used by OrientDB here is reflection.

    As an example:

    try {
        OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
        if (Class.forName("com.sun.management.OperatingSystemMXBean").isInstance(os)) {
            Method memorySize = os.getClass().getDeclaredMethod("getTotalPhysicalMemorySize");
            memorySize.setAccessible(true);
            return (Long) memorySize.invoke(os);
        }
    } catch (Exception e) {
    }
    
    0 讨论(0)
  • 2020-12-18 21:56

    The best solution i found for this one is :

    • Go to the Build Path settings in the project properties.

    • Remove the JRE System Library

    • Add it back; Select "Add Library" and select the JRE System Library.

    https://stackoverflow.com/a/2174607/1572446

    0 讨论(0)
  • 2020-12-18 22:12

    This is not a problem of license agreements. It is just Eclipse trying to protect you from using classes that are not part of the official JDK API (but rather, part of Oracle/Sun's JVM implementation).

    Is there a particular reason that you need to class cast (rather than using the "official" interface java.lang.management.OperatingSystemMXBean)?

    If you want to make sure that your application continues to run when the expected MXBean is not available, you could add some try/catch logic to gracefully handle a ClassCastException.

    0 讨论(0)
提交回复
热议问题