Is there cast in Java similar to in C++

后端 未结 7 981
小蘑菇
小蘑菇 2020-12-04 01:54

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++ ?

7条回答
  •  醉梦人生
    2020-12-04 02:42

    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

提交回复
热议问题