集册 Java实例教程 调用方法句柄

调用方法句柄

欢马劈雪     最近更新时间:2020-01-02 10:19:05

602
调用方法句柄


//package com.nowjava;

import java.lang.invoke.CallSite;

import java.lang.invoke.ConstantCallSite;
/**来自 
 时代Java - nowjava.com**/

import java.lang.invoke.MethodHandle;

import java.lang.invoke.MethodHandles;

import java.lang.invoke.MethodType;


public class Main {

    /**

     * mName: println mType: (Object,String)V declaringClass: Base.class

     */

    public static CallSite simpleCall(MethodHandles.Lookup lookup,

            String mName, MethodType mType, Class<?> declaringClass) {


        try {

            // MethodType virtualType = MethodType.methodType(Void.TYPE,

            // String.class);

            MethodType virtualType = mType.dropParameterTypes(0, 1);

            MethodHandle mHandle = lookup.findVirtual(declaringClass,

                    mName, virtualType);
//n o w j a   v  a . c o m - 时  代  Java 提供

            MethodHandle asType = mHandle.asType(mType);

            CallSite callSite = new ConstantCallSite(asType);

            return callSite
展开阅读全文