3

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?

BillRobertson42
  • 12,602
  • 4
  • 40
  • 57

1 Answers1

4

I'm not familiar with the invoke API, so take this answer with a grain of salt, but why can't you just use the VarHandle returned by MethodHandles.arrayElementVarHandle? Doing the following seems to access the elements:

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    VarHandle varHandle = MethodHandles.arrayElementVarHandle(int[].class);

    int[] array = new int[5];

    printArray(array);
    varHandle.set(array, 2, 5);
    printArray(array);

    System.out.println(varHandle.get(array, 2));
  }

  private static void printArray(int[] array) {
    System.out.println(Arrays.toString(array));
  }

}

Output:

[0, 0, 0, 0, 0]
[0, 0, 5, 0, 0]
5
Slaw
  • 37,820
  • 8
  • 53
  • 80
  • I think you're on to something. I was so caught up in lookup mechanism that bound the VarHandle to the value that I was expecting to bind to the array directly instead of just passing the member variable to the VarHandle. Will check that out. – BillRobertson42 Oct 25 '18 at 02:04
  • God, how terrible this API is.. I would never have figured this out just by inspecting the method signatures.. – devoured elysium Jul 26 '21 at 03:12