Home  >  Article  >  Java  >  How do we create an instance of VarHandle in Java 9?

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

王林
王林forward
2023-09-17 21:53:081212browse

在Java 9中,我们如何创建VarHandle的实例?

Generally speaking, Variable handle is just a typed reference to a variable. It will be an array element of the class, an instance or a static field . The VarHandle class can provide write and read access to variables under specific conditions. They are immutable and have no visible conditions. Additionally, they cannot be subdivided, each VarHandle has a generic type T, which is the type of each variable represented by this VarHandle. The goal of VarHandle is to define a standard for calling the equivalent sum of java.util.concurrent.atomic and sun.misc.Unsafe operations on a field. Array elements.

In the following example, we can use the 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 {
         <strong>VarHandle </strong>fieldHandle = <strong>MethodHandles.lookup().in</strong>(Student.class).<strong>findVarHandle</strong>(Student.class, "<strong>studentId</strong>", int.class);
         System.out.println("VarHandle instance created successfully!!!");
      } catch (NoSuchFieldException | IllegalAccessException e) {
         e.printStackTrace();
      }
   }
}

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

Output

<strong>VarHandle instance created successfully!!!</strong>

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete