简体   繁体   English

如何在 Java 9+ 中创建一个 varhandle 来访问数组的元素

[英]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.我正在尝试转换一些使用 Unsafe 对类中的局部变量执行内存访问的代码,并且该代码似乎也使用 Unsafe 来访问数组中的元素。

I have the following code to create a VarHandle for the single elements, and it seems to work.我有以下代码来为单个元素创建一个 VarHandle,它似乎有效。

// 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.我还读到您还可以使用 VarHandles 来访问数组元素。 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.使用上面的代码,我可以获得对整个数组的引用,但我无法弄清楚如何构造 VarHandle 以便我可以使用它来访问数组元素。

I see that MethodHandle has the the arrayElementVarHandle(int[].class) which returns a VarHandle.我看到 MethodHandle 具有返回 VarHandle 的arrayElementVarHandle(int[].class) Maybe I need to somehow convert the VarHandle back to a MethodHandle and then call arrayElementVarHandle() on that to be able to do this?也许我需要以某种方式将 VarHandle 转换回 MethodHandle 然后调用arrayElementVarHandle()才能做到这一点?

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 ?我不熟悉调用 API,所以对这个答案VarHandle ,但为什么你不能只使用VarHandle返回的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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