【反射】方法句柄

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();
        }
    }
}
posted @ 2022-10-03 10:57  xl4ng  阅读(20)  评论(0编辑  收藏  举报