Home  >  Article  >  Java  >  What is the importance of MethodHandles class in Java 9?

What is the importance of MethodHandles class in Java 9?

WBOY
WBOYforward
2023-08-25 17:21:091083browse

在Java 9中,MethodHandles类的重要性是什么?

MethodHandles class was introduced in the Java 7 version. This class mainly adds some static methods to improve the functionality and is divided into several categories, such as Find methods used to create method handles to access methods and fields, Combined methods Combine or convert existing method handles into new method handles, and Factory methods are used to create method handles that simulate other common JVM operations or control flow patterns. In Java 9, the MethodHandles class was enhanced, many changes were introduced, and new static methods were added, such as arrayLength(), arrayConstructor() , zero(), etc. The Chinese translation of

Grammar

<strong>public class MethodHandles extends Object</strong>

Example

is:

Example

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;

public class MethodHandlesTest {
   public void MethodHandle1() {
      try {
         <strong>MethodHandle </strong>methodHandleLength = <strong>MethodHandles</strong>.<strong>arrayLength</strong>(int[].class);
         int[] array = new int[] {5, 10, 15, 20};
         int arrayLength = (int) methodHandleLength.<strong>invoke</strong>(array);
         System.out.println("Length of Array using Method Handle is: " + arrayLength);

         <strong>MethodHandle </strong>methodHandleConstructor = <strong>MethodHandles.arrayConstructor</strong>(int[].class);
         int[] newArray = (int[]) methodHandleConstructor.<strong>invoke</strong>(3);
         System.out.println("Array Constructed using Method Handle of Size: " + newArray.length);

         int x = (int) <strong>MethodHandles.zero</strong>(int.class).<strong>invoke()</strong>;
         System.out.println("Default Value of Primitive Integer using Method Handles is: " + x);
         String y = (String) <strong>MethodHandles.zero</strong>(String.class).<strong>invoke()</strong>;
         System.out.println("Default Value of String using Method Handles is: " + y);
      } catch(Throwable e) {
         e.printStackTrace();
      }
   }
   public static void main(String args[]) {
      new MethodHandlesTest().MethodHandle1();
   }
}

Output

<strong>Length of Array using Method Handle is: 4
Array Constructed using Method Handle of Size: 3
Default Value of Primitive Integer using Method Handles is: 0
Default Value of String using Method Handles is: null</strong>

The above is the detailed content of What is the importance of MethodHandles class 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