What I do is create a regular DirectByteBuffer and change its address.
Field address = Buffer.class.getDeclaredField("address"); address.setAccessible(true); Field capacity = Buffer.class.getDeclaredField("capacity"); capacity.setAccessible(true); ByteBuffer bb = ByteBuffer.allocateDirect(0).order(ByteOrder.nativeOrder()); address.setLong(bb, addressYouWantToSet); capacity.setInt(bb, theSizeOf);
From now on, you can access ByteBuffer by referencing the base address. I did this to access memory on network adapters for a null copy and worked fine.
You can create a DirectByteBuffer for your address directly, but this is more obscure.
An alternative is to use Unsafe (this only works in the OpenJDK / HotSpot JVM and in native byte order)
Unsafe.getByte(address); Unsafe.getShort(address); Unsafe.getInt(address); Unsafe.getLong(address);
source share