首頁  >  文章  >  Java  >  在Java 9中,MethodHandles類別的重要性是什麼?

在Java 9中,MethodHandles類別的重要性是什麼?

WBOY
WBOY轉載
2023-08-25 17:21:091083瀏覽

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

MethodHandles 類別是在Java 7版本中引入的。這個類別主要添加了一些靜態方法 來改進功能,並分為幾個類別,例如查找方法 用於建立方法句柄以存取方法和字段,組合方法將現有的方法句柄組合或轉換為新的方法句柄,以及工廠方法用於建立模擬其他常見JVM操作或控制流模式的方法句柄。在Java 9中,MethodHandles 類別進行了增強,引入了許多變化,並添加了新的靜態方法,如arrayLength()arrayConstructor()zero()等。

語法

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

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();
   }
}

輸出

<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>
#

以上是在Java 9中,MethodHandles類別的重要性是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除