Java动态类型方法的实现

import com.madg.jvm.Test;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.util.ArrayList;
import java.util.List;

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


public class Main {

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

    public static void main(String[] args)
    {
        for (int i = 0; i < 10; i++) {
            //无论obj最终是哪个实现类,下面这句都能正确的调用到println方法
            Object obj=System.currentTimeMillis()%2==0 ?System.out :new ClassA();
            try {
                getPrintlnMH(obj).invokeExact("madg"+obj.toString());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }

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

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

运行结果如下:

madgjava.io.PrintStream@24d46ca6
madgjava.io.PrintStream@24d46ca6
madgMain$ClassA@28a418fc
madgMain$ClassA@5305068a
madgMain$ClassA@1f32e575
madgMain$ClassA@279f2327
madgjava.io.PrintStream@24d46ca6
madgjava.io.PrintStream@24d46ca6
madgjava.io.PrintStream@24d46ca6
madgjava.io.PrintStream@24d46ca6

Process finished with exit code 0

 

 

你可能感兴趣的:(java)