Home> Java> javaTutorial> body text

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

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

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

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.

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

Output

VarHandle instance created successfully!!!
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!