วิธีจัดการ แนะนำคลาสใน Java 7 รุ่น คลาสนี้เพิ่ม สแตติก . บางส่วนเป็นหลัก วิธีการ เพื่อการทำงานที่ดีขึ้น และแบ่งออกเป็นหลายประเภท เช่น วิธีค้นหา ที่ช่วยในการสร้างเมธอดสำหรับเมธอดและฟิลด์ เมธอดของคอมบิเนเตอร์ ที่รวมหรือแปลงวิธีการที่มีอยู่ก่อนให้เป็นวิธีการใหม่ และวิธีการจากโรงงาน เพื่อสร้างวิธีการจัดการที่จำลองการดำเนินการ JVM ทั่วไปอื่น ๆ หรือรูปแบบการควบคุมการไหล วิธีจัดการ คลาสได้รับการปรับปรุงใน Java 9 เพื่อแนะนำการเปลี่ยนแปลงมากมายและเพิ่มวิธีการแบบสแตติกใหม่เช่น arrayLength() , arrayConstructor() , ศูนย์() และอื่นๆ
ไวยากรณ์
public class MethodHandles extends Object
ตัวอย่าง
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
public class MethodHandlesTest {
public void MethodHandle1() {
try {
MethodHandle methodHandleLength = MethodHandles.arrayLength(int[].class);
int[] array = new int[] {5, 10, 15, 20};
int arrayLength = (int) methodHandleLength.invoke(array);
System.out.println("Length of Array using Method Handle is: " + arrayLength);
MethodHandle methodHandleConstructor = MethodHandles.arrayConstructor(int[].class);
int[] newArray = (int[]) methodHandleConstructor.invoke(3);
System.out.println("Array Constructed using Method Handle of Size: " + newArray.length);
int x = (int) MethodHandles.zero(int.class).invoke();
System.out.println("Default Value of Primitive Integer using Method Handles is: " + x);
String y = (String) MethodHandles.zero(String.class).invoke();
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();
}
} ผลลัพธ์
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