All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jadira.reflection.access.invokedynamic.InvokeDynamicMethodAccess Maven / Gradle / Ivy

There is a newer version: 7.0.0.CR1
Show newest version
package org.jadira.reflection.access.invokedynamic;

import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;

import org.dynalang.dynalink.DefaultBootstrapper;
import org.jadira.reflection.access.api.MethodAccess;

public class InvokeDynamicMethodAccess implements MethodAccess {

	private String methodName;
	
	private Method method;
	private Class declaringClass;
	private Class returnType;

	CallSite methodCallSite;
	
	MethodHandle mh;
	
	@SuppressWarnings("unchecked")
	private InvokeDynamicMethodAccess(Method m) {
		
		this.methodName = m.getName();
		
		this.declaringClass = (Class) m.getDeclaringClass();	
		this.method = m;

		this.returnType = (Class) m.getReturnType();
		
		methodCallSite = DefaultBootstrapper.publicBootstrap(null, "dyn:getMethod:" + methodName, MethodType.methodType(returnType, declaringClass, method.getParameterTypes()));	
		mh = methodCallSite.dynamicInvoker();		
	}
	
	public static  InvokeDynamicMethodAccess get(Method m) {
		
		return new InvokeDynamicMethodAccess(m);
	}
	
	@Override
	public Class declaringClass() {
		return declaringClass;
	}

	@Override
	public Class returnClass() {
		return returnType;
	}

	@Override
	public Method method() {
		return method;
	}
	
	@Override
	public Object invoke(Object target, Object... args) throws IllegalArgumentException {
		
	    try {
            return mh.invokeExact(target, args);
        } catch (Throwable e) {
            throw new IllegalArgumentException("Problem invoking {" + method.getName() + "} of object {"
                    + System.identityHashCode(target) + "}: " + e.getMessage(), e);
        }
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy