How can we create an instance of VarHandle in Java 9?

JavaObject Oriented ProgrammingProgramming

In general, a Variable Handle is simply typed reference to a variable. It will be an array element, an instance or static field of the class. VarHandle class can provide write and read access to variables under specific conditions. These are immutable and have no visible condition. In addition, they can't be sub-classified, and each VarHandle has a generic type T, which is the type of each variable represented by this VarHandle. The objective of VarHandle is to define a standard for calling equivalents of java.util.concurrent.atomic and sun.misc.Unsafe operations on fields and array elements.

In the below example, we can use MethodHandle.lookup() method to create a VarHandle instance.

Example

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

public class VarHandleInstanceTest {
   public static void main(String args[]) {
      try {
         VarHandle fieldHandle = MethodHandles.lookup().in(Student.class).findVarHandle(Student.class, "studentId", int.class);
         System.out.println("VarHandle instance created successfully!!!");
      } catch (NoSuchFieldException | IllegalAccessException e) {
         e.printStackTrace();
      }
   }
}

// Stundent class
class Student {
   protected int studentId;
   private String[] marks;
   public Student() {
      studentId = 0 ;
      marks = new String[] {"75" , "85" , "95"} ;
   }
}

Output

VarHandle instance created successfully!!!
raja
Published on 16-Apr-2020 17:41:28
Advertisements