简体   繁体   中英

How to create a varhandle to access elements of an array in Java 9+

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM