public class Person {
private String name = "小张";
public void say(String c) {
System.out.println(c);
}
public void say() {
System.out.println("hello," + name);
}
}
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class UseMethodHandle {
public static void main(String[] args) {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType mtCons = MethodType.methodType(void.class);
try {
//得到Person类的构造方法的方法句柄
MethodHandle mhCons = lookup.findConstructor(Person.class, mtCons);
//调用构造方法,得到Person类的对象
Person p = (Person)mhCons.invokeExact();
//开始准备调用Person对象的say方法
MethodType mt = MethodType.methodType(void.class,String.class);
MethodHandle mh = lookup.findVirtual(Person.class, "say", mt);
mh.invokeExact(p,"hello");
}catch (Throwable e){
e.printStackTrace();
}
}
}
标签:反射,句柄,void,public,Person,say,MethodType,方法,class
From: https://www.cnblogs.com/xl4ng/p/16750162.html