Use the java class sun.misc.Unsafe, some of the methods you may be interested in are :
public native long getAddress(long address);
public native void putAddress(long address, long value);
public native long allocateMemory(long size);
public native long reallocateMemory(long l, long l1);
public native void setMemory(long l, long l1, byte b);
public native void copyMemory(long l, long l1, long l2);
You can't instantiate the class directly as it has a private constructor, so you will have to create an instance like this :
Unsafe unsafe = null;
try {
Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (sun.misc.Unsafe) field.get(null);
} catch (Exception e) {
throw new AssertionError(e);
}
you can then call
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class Direct {
public static void main(String... args) {
Unsafe unsafe = null;
try {
Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (sun.misc.Unsafe) field.get(null);
} catch (Exception e) {
throw new AssertionError(e);
}
long value = 12345;
byte size = 1;
long allocateMemory = unsafe.allocateMemory(size);
unsafe.putAddress(allocateMemory, value);
long readValue = unsafe.getAddress(allocateMemory);
System.out.println("read value : " + readValue);
}
}
Output :
read value : 12345