I'm attempting to convert some code that uses Unsafe to perform memory accesses on local variables in classes, and the code also seems to use Unsafe to access elements in an array.
I have the following code to create a VarHandle for the single elements, and it seems to work.
// where self is a class object, and VarName is the name of the class member
return MethodHandles.privateLookupIn(self, MethodHandles.lookup()).
findVarHandle(self, varName, self);
I've also read that you can also use VarHandles to access array elements. Using the code above, I can get a reference to the entire array, but I can't quite puzzle out how to construct the VarHandle such that I can use it to access array elements.
I see that MethodHandle has the the arrayElementVarHandle(int[].class)
which returns a VarHandle. Maybe I need to somehow convert the VarHandle back to a MethodHandle and then call arrayElementVarHandle()
on that to be able to do this?