Home » Java » java – How to create a TriFunction that call a one parameter method dynamically?-Exceptionshub

java – How to create a TriFunction that call a one parameter method dynamically?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to create a TriFunction at runtime that invoke a one parameter method but I obtain this exception:

java.lang.invoke.LambdaConversionException: Incorrect number of parameters for instance method invokeVirtual java.lang.ClassLoader.getDefinedPackage:(String)Package; 0 captured parameters, 3 functional interface method parameters, 2 implementation parameters

Here is my code:

Lookup classLoaderConsulter = MethodHandles.lookup().in(MyClass.class);
            MethodHandle methodHandle = classLoaderConsulter.unreflect(ClassLoader.class.getDeclaredMethod("getDefinedPackage", String.class));
            MethodType packageRetrieverParams = MethodType.methodType(Package.class, ClassLoader.class, Object.class, String.class);
            packageRetriever = (ThrowingTriFunction<ClassLoader, Object, String, Package>)LambdaMetafactory.metafactory(
                    classLoaderConsulter, "apply", MethodType.methodType(ThrowingTriFunction.class), packageRetrieverParams,
                    methodHandle, methodHandle.type())
                    .getTarget().invokeExact();
import java.util.Objects;
import java.util.function.Function;

@FunctionalInterface
public interface ThrowingTriFunction<P0, P1, P2, R> {

    R apply(P0 p0, P1 p1, P2 p2) throws Throwable;

    default <V> ThrowingTriFunction<P0, P1, P2, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (P0 p0, P1 p1, P2 p2) -> after.apply(apply(p0, p1, p2));
    }
}

How can I solve?

How to&Answers: