package org.suych;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class MethodHandleTest {
private String name;
// 构造方法
public MethodHandleTest(String name) {
this.name = name;
}
// 公共方法
public String publicTest() {
return name + "'publicTest";
}
// 静态方法
public static String publicStaticTest() {
return "'publicStaticTest";
}
// 私有方法
private String test(int param) {
switch (param) {
case 1:
return "suych1";
case 2:
return "suych2";
case 3:
return "suych3";
default:
return "suych4";
}
}
// Get方法
public String getName() {
return name;
}
// Set方法
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) throws Throwable {
// 构造方法
MethodType mtConstructor = MethodType.methodType(void.class, String.class);
MethodHandle mhConstructor = MethodHandles.lookup().findConstructor(MethodHandleTest.class, mtConstructor);
MethodHandleTest businessHandle = (MethodHandleTest) mhConstructor.invokeExact("suych");
System.out.println(businessHandle.getName());
// 公共方法
MethodType mtPublic = MethodType.methodType(String.class);
MethodHandle mhPublic = MethodHandles.lookup().findVirtual(MethodHandleTest.class, "publicTest", mtPublic);
String resultPublic = (String) mhPublic.invokeExact(businessHandle);
System.out.println(resultPublic);
// 静态方法
MethodType mtPublicStatic = MethodType.methodType(String.class);
MethodHandle mhPublicStatic = MethodHandles.lookup().findStatic(MethodHandleTest.class, "publicStaticTest",
mtPublicStatic);
String resultPublicStatic = (String) mhPublicStatic.invokeExact();
System.out.println(resultPublicStatic);
// 私有方法
MethodType mtPrivate = MethodType.methodType(String.class, int.class);
MethodHandle mhPrivate = MethodHandles.lookup().findSpecial(MethodHandleTest.class, "test", mtPrivate,
MethodHandleTest.class);
String resultPrivate = (String) mhPrivate.invokeExact(businessHandle, 1);
System.out.println(resultPrivate);
// Set方法
MethodHandle mhSet = MethodHandles.lookup().findSetter(MethodHandleTest.class, "name", String.class);
mhSet.invokeExact(businessHandle, "A");
System.out.println(businessHandle.name);
// Get方法
MethodHandle mhGet = MethodHandles.lookup().findGetter(MethodHandleTest.class, "name", String.class);
String resultGet = (String) mhGet.invokeExact(businessHandle);
System.out.println(resultGet);
}
}
执行结果:
suych
suych'publicTest
'publicStaticTest
suych1
A
A