Mister Dai
Mister Dai

Reputation: 816

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

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 OperatingSystemMXBean is not accessible due to restriction on required library C:\Program Files\Java\jre6\lib\rt.jar

From this line of code...

com.sun.management.OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean();

I've found ways around this but I'm worried about the restriction warning. This code is for my open source project (CfTracker) and I don't want to work around this restriction if I'm going to be breaking some sort of license agreement. Can anyone help me understand this?

Upvotes: 16

Views: 39058

Answers (4)

IvanRF
IvanRF

Reputation: 7265

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) {
}

Upvotes: 4

Shivam Verma
Shivam Verma

Reputation: 426

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

Upvotes: 9

Zohaib
Zohaib

Reputation: 417

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.

Upvotes: 16

Thilo
Thilo

Reputation: 262554

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.

Upvotes: 14

Related Questions