I get in my function message array of bytes and type of object, I need to restore object from bytes. Is there in Java any cast like in C++ ?
If you really want to take a block of memory, and reinterpret it as a java object, you can achieve that through sun.misc.Unsafe
.
You'd need to iterate the class/type of the object, find all the valid fields you'd need to set, read their specific types out of the off-heap memory buffer, and set them via reflection.
It's not something I'd recommend, making use of other serialization mechanics would be a much better alternative.
Edit: Something like this perhaps:
class Test {
int x;
int y;
}
public static void main(String[] args) throws Exception {
final Unsafe unsafe = Unsafe.getUnsafe();
final int count = 2;
final long address = unsafe.allocateMemory(Integer.BYTES * count);
for (int i = 0; i < count; ++i) {
unsafe.putInt(address + i * Integer.BYTES, ThreadLocalRandom.current().nextInt(0, 10));
}
final Class klass = Test.class;
final Test test = klass.newInstance();
int i = 0;
for (final Field f : klass.getDeclaredFields()) {
f.setAccessible(true);
f.putInt(test, unsafe.getInt(address + i * Integer.BYTES));
++i;
}
}
Of course you easily reinterpret these primitives into anything. I don't even have to Unsafe#putInt
, but obviously I need ints according to Test