JDK1.8动态代理与反射的区别

package com.memory.invoke;

import javax.swing.plaf.synth.SynthEditorPaneUI;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;

import static java.lang.invoke.MethodHandles.lookup;

public class MethodHandleTest {

    static class ClassA{
        public void println(String s){
            System.out.println(s);
        }
    }

    public static void main(String[] args) {
        Object obj = System.currentTimeMillis()%2==0?System.out:new ClassA();
        try {
            getPrintlnMH(obj).invokeExact("icyfenix");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    private static MethodHandle getPrintlnMH(Object reveiver) throws Throwable{
        MethodType mt = MethodType.methodType(void.class,String.class);

        return lookup().findVirtual(reveiver.getClass(),"println",mt).bindTo(reveiver);
    }
}

你可能感兴趣的:(JAVA)