call method handle - Java Reflection

Java examples for Reflection:Method

Description

call method handle

Demo Code


//package com.java2s;
import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class Main {
    /**//from w  ww .j av a 2s.  c o m
     * 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);

            MethodHandle asType = mHandle.asType(mType);
            CallSite callSite = new ConstantCallSite(asType);
            return callSite;
        } catch (NoSuchMethodException | IllegalAccessException e) {
            throw new LinkageError("Link error:", e);
        }

    }
}

Related Tutorials