Generally speaking,Variable handleis just a typed reference to a variable. It will be anarrayelement of the class, aninstanceor astaticfield. TheVarHandleclass can provide write and read access to variables under specific conditions. They areimmutableand have no visible conditions. Additionally, they cannot be subdivided, eachVarHandlehas ageneric typeT, which is the type of each variable represented by thisVarHandle. The goal ofVarHandleis to define a standard for calling the equivalent sum ofjava.util.concurrent.atomicandsun.misc.Unsafeoperations on a field. Array elements.
In the following example, we can use theMethodHandle.lookup()method to create aVarHandleinstance.
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"} ; } }
VarHandle instance created successfully!!!
The above is the detailed content of How do we create an instance of VarHandle in Java 9?. For more information, please follow other related articles on the PHP Chinese website!