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

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

王林
Release: 2023-09-17 21:53:08
forward
1239 people have browsed it

在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"} ;
   }
}
Copy after login

Output

<strong>VarHandle instance created successfully!!!</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template