Does Java Allow Direct Memory Access

I know C# allows you to use pointers in the unsafe context. But does Java have some similar memory access method?

Java does not have pointers (for good reasons), so if there is a similar memory access method, what would it be exactly?


Well, there is a sun.misc.Unsafe class. It allows direct memory access, so you can implement some magic like reinterpret casts and so on. The thing is you need to use hacky reflection approach to get the instance and this class is not realy well documented. In general you need a very good reason to use this kind of tool in production code.

Here's an example how to get it:

Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);

There are 105 methods, allowing different low-level stuff. These methods are devoted to direct memory access:

  • allocateMemory
  • copyMemory
  • freeMemory
  • getAddress
  • getInt
  • Edit: this method may be incompatible with future versions of OpenJDK or any other JVM implementation, as it is not a part of the public API. Although a lot of OpenJDK code uses Unsafe, it's implementation still is a subject of change without any notice. Thanks to all who point this out in comments.


    No, you can't.

    The closest you can get is to use JNI and call a C function that returns the data at a given memory location.


    No, Java does not have any in-language mechanism for accessing arbitrary memory locations. JNI can perform whatever (unsafe and unmanaged) operations the OS allows, but that's as close as you get.

    链接地址: http://www.djcxy.com/p/31664.html

    上一篇: Visual Studio用删除的指针做什么,为什么?

    下一篇: Java是否允许直接内存访问?