问题
Lets sat I have an object i'd like to store in a direct byte buffer. I'd like to able access parts of the object from the direct byte buffer without de-serializing the whole object. Is there a safe way to do this?
I'm thinking you could somehow capture the byte array offsets when serializing the object, then once its been written to the direct byte buffer you would adjust these offsets according to the offset of the direct byte buffer. I'm not sure if its possible to do this...
回答1:
The real question is not, is this possible, since it almost certainly is, but why do you want to do this in the first place?
If you just want to access a few fields from the object, the easiest way to do that will be to deserialize it and then copy those few fields out.
The only reason you might want to avoid the (de-)serialization is for speed, but if this is in one of your busy loops, then you are lost anyway. If the network (de-)serialization is the issue, then you should design your protocol better.
回答2:
I think the best way of doing is like so, its a bit of a work around, but should be effective.
interface OffsetMemberMap {
Map<String,Long> offsetMemberMap();
}
The idea is to create objects that implement the above interface, this map will store memory addresses against Strings for each member. Child objects would be created first and once added to a DirectByteBuffer the offset position would be stored in the parent within this map. In order to access a specific member the user would need to supply the string which addresses that member and thus only what's needed would be de-serialized. This would allow you to store large linked objects in DirectByteBuffers whilst being able to only serialize/de-serialize the bits you need when writing/reading.
来源:https://stackoverflow.com/questions/19446266/what-is-the-safest-way-to-use-direct-byte-buffers-in-java