JA getting instances of unsafe classes and canceling Eclipse compilation errors and warnings

Source: Internet
Author: User

A class Sun.misc.Unsafe is provided in the JRE's Rt.jar, although this class is not recommended for its security, and is subject to many restrictions;

There are many occasions when we really need the power of this class to provide. Many of the classes under the NIO and concurrent packages under the JDK library are using unsafe

Classes, such as Atomicinteger and Abstractqueuedsynchronizer.

This class is strictly restricted in the JDK source code, and we cannot get instances of the class in the usual new way, nor can we pass the Unsafe.getunsafe

() to gets the instance. But we can get an instance of the unsafe class in our application code through reflection:

public static unsafe getunsafeinstance () throws exception{        //Get the Unsafe class under Rt.jar by reflection        Field theunsafeinstance = Unsafe.class.getDeclaredField ("Theunsafe");        Theunsafeinstance.setaccessible (true);        return (unsafe) theunsafeinstance.get (null); is the equivalent        return (unsafe) theunsafeinstance.get (unsafe.class);}

After Eclipse has finished writing this function, an error or warning message appears: Access restriction:the type Unsafe is not accessible

Due to restriction on required library C:\Program Files\java\jdk1.6.0_32\jre\lib\rt.jar.

Although this code will be reported in Eclipse or error, but it can be run. We can set the following in eclipse to cancel the police

or error: Window-->preferences-->java-->compiler-->errors/warnings, will be inside the deprecated and restricted API

of the Forbidden references (access rules) is set to ignore so that Eclipse does not report a warning or error.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.