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.