What is Variable Handle in Java 9?

JavaObject Oriented ProgrammingProgramming

Variable Handle is a variable or reference to a set of variables, including other components of a static field, non-static fields, and outer array elements in the heap data structure. It means that Variable Handle is similar to the existing Method Handle. It can be represented by using java.lang.invoke.VarHandle class. We can use java.lang.invoke.MethodHandles.Lookup static factory method to create Variable Handle objects. It can also be used to access a single element in the array, and byte[] array.

Syntax

public abstract class VarHandle extends Object

Example

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

public class VarHandleTest {
   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
raja
Published on 13-Mar-2020 13:47:12
Advertisements