Java Code Examples for java.lang.invoke.MethodHandle#invokeWithArguments()

The following examples show how to use java.lang.invoke.MethodHandle#invokeWithArguments() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netty-rest   File: MethodHandleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testName() throws Exception {

    Method meth = Foo.class.getDeclaredMethods()[0];

    MethodHandles.Lookup lookup = MethodHandles.lookup();
    MethodHandle mh = lookup.unreflect(meth);

    Foo foo = new Foo();
    String myStr = "aaa";
    Integer myInt = new Integer(10);
    Object[] myArray = {foo, myStr, myInt};

    try {
        mh.invokeWithArguments(myArray); // throws Exception
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}
 
Example 2
Source Project: bazel   File: LambdaClassMaker.java    License: Apache License 2.0 6 votes vote down vote up
public void generateLambdaClass(
    String invokerInternalName,
    LambdaInfo lambdaInfo,
    MethodHandle bootstrapMethod,
    ArrayList<Object> bsmArgs)
    throws IOException {
  // Invoking the bootstrap method will dump the generated class.  Ignore any pre-existing
  // matching files, which can come from desugar's implementation using classes being desugared.
  existingPaths.addAll(findUnprocessed(invokerInternalName + "$$Lambda$"));
  try {
    bootstrapMethod.invokeWithArguments(bsmArgs);
  } catch (Throwable e) {
    throw new IllegalStateException(
        "Failed to generate lambda class for class "
            + invokerInternalName
            + " using "
            + bootstrapMethod
            + " with arguments "
            + bsmArgs,
        e);
  }

  Path generatedClassFile = getOnlyElement(findUnprocessed(invokerInternalName + "$$Lambda$"));
  generatedClasses.put(generatedClassFile, lambdaInfo);
  existingPaths.add(generatedClassFile);
}
 
Example 3
public static void testVarargsArray() throws Throwable {
    final int MIN = START_ARITY;
    final int MAX = MAX_ARITY-2;  // 253+1 would cause parameter overflow with 'this' added
    for (int nargs = MIN; nargs <= MAX; nargs = nextArgCount(nargs, 17, MAX)) {
        MethodHandle target = MethodHandleHelper.varargsArray(nargs);
        Object[] args = new Object[nargs];
        for (int i = 0; i < nargs; i++)
            args[i] = "#"+i;
        Object res = target.invokeWithArguments(args);
        assertArrayEquals(args, (Object[])res);
    }
}
 
Example 4
/**
 * Tests that MHs.eCA method works correctly with MHs with multiple arguments.
 * @throws Throwable
 */
public static void testMultipleArgs() throws Throwable {
    int arity = 1 + RNG.nextInt(Helper.MAX_ARITY / 2 - 2);
    int arityMinus = RNG.nextInt(arity);
    int arityPlus = arity + RNG.nextInt(Helper.MAX_ARITY / 2 - arity) + 1;
    MethodType mType = Helper.randomMethodTypeGenerator(arity);
    MethodType mTypeNew = Helper.randomMethodTypeGenerator(arity);
    MethodType mTypeNewMinus = Helper.randomMethodTypeGenerator(arityMinus);
    MethodType mTypeNewPlus = Helper.randomMethodTypeGenerator(arityPlus);
    Class<?> rType = mType.returnType();
    MethodHandle original;
    if (rType.equals(void.class)) {
        MethodType mt = MethodType.methodType(void.class);
        original = MethodHandles.publicLookup()
                .findStatic(THIS_CLASS, "retVoid", mt);
    } else {
        Object rValue = Helper.castToWrapper(1, rType);
        original = MethodHandles.constant(rType, rValue);
    }
    original = Helper.addTrailingArgs(original, arity, mType.parameterList());
    MethodHandle target = MethodHandles
                .explicitCastArguments(original, mTypeNew);
    Object[] parList = Helper.randomArgs(mTypeNew.parameterList());
    for (int i = 0; i < parList.length; i++) {
        if (parList[i] instanceof String) {
            parList[i] = null; //getting rid of Stings produced by randomArgs
        }
    }
    target.invokeWithArguments(parList);
    checkForWrongMethodTypeException(original, mTypeNewMinus);
    checkForWrongMethodTypeException(original, mTypeNewPlus);
}
 
Example 5
private void testArities(Class<? extends Object[]> cls,
                         int minArity,
                         int maxArity,
                         int iterations) throws Throwable {
    boolean verbose = (cls == Object[].class);
    for (int arity = minArity; arity <= maxArity; arity++) {
        if (verbose)  System.out.println("arity="+arity);
        MethodHandle mh = MH_hashArguments(cls, arity);
        MethodHandle mh_VA = mh.asSpreader(cls, arity);
        MethodHandle mh_VA_h = mh.asSpreader(0, cls, arity-1);
        assert(mh_VA.type().parameterType(0) == cls);
        assert(mh_VA_h.type().parameterType(0) == cls);
        testArities(cls, arity, iterations, verbose, mh, mh_VA, mh_VA_h);
        // mh_CA will collect arguments of a particular type and pass them to mh_VA
        MethodHandle mh_CA = mh_VA.asCollector(cls, arity);
        MethodHandle mh_VA2 = mh_CA.asSpreader(cls, arity);
        MethodHandle mh_VA2_h = mh_CA.asSpreader(0, cls, arity-1);
        assert(mh_CA.type().equals(mh.type()));
        assert(mh_VA2.type().equals(mh_VA.type()));
        if (cls != Object[].class) {
            try {
                mh_VA2.invokeWithArguments(new Object[arity]);
                throw new AssertionError("should not reach");
            } catch (ClassCastException | WrongMethodTypeException ex) {
            }
        }
        int iterations_VA = iterations / 100;
        testArities(cls, arity, iterations_VA, false, mh_CA, mh_VA2, mh_VA2_h);
    }
}
 
Example 6
@Override
public void logX(java.lang.System.Logger logger,
        java.lang.System.Logger.Level level, Object... args) {
    try {
        MethodHandle handle = lookup.findVirtual(spiLoggerClass,
                method, mt).bindTo(logger);
        final int last = mt.parameterCount()-1;
        boolean isVarargs = mt.parameterType(last).isArray();

        args = makeArgs(level, args);

        final StringBuilder builder = new StringBuilder();
        builder.append(logger.getClass().getSimpleName()).append('.')
                .append(this.method).append('(');
        String sep = "";
        int offset = 0;
        Object[] params = args;
        for (int i=0; (i-offset) < params.length; i++) {
            if (isVarargs && i == last) {
                offset = last;
                params = (Object[])args[i];
                if (params == null) break;
            }
            Object p = params[i - offset];
            String quote = (p instanceof String) ? "\"" : "";
            p = p instanceof Level ? "Level."+p : p;
            builder.append(sep).append(quote).append(p).append(quote);
            sep = ", ";
        }
        builder.append(')');
        if (verbose) System.out.println(builder);
        handle.invokeWithArguments(args);
    } catch (Throwable ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 7
/**
 * Tests that MHs.explicitCastArguments does incorrect type checks for
 * VarargsCollector. Bug 8066746.
 *
 * @throws java.lang.Throwable
 */
public static void testVarargsCollector() throws Throwable {
    MethodType mt = MethodType.methodType(String[].class, String[].class);
    MethodHandle mh = MethodHandles.publicLookup()
            .findStatic(THIS_CLASS, "f", mt);
    mh = MethodHandles.explicitCastArguments(mh,
            MethodType.methodType(Object.class, Object.class));
    mh.invokeWithArguments((Object) (new String[]{"str1", "str2"}));
}
 
Example 8
/**
 * Tests that MHs.explicitCastArguments does incorrect type checks for
 * VarargsCollector. Bug 8066746.
 *
 * @throws java.lang.Throwable
 */
public static void testVarargsCollector() throws Throwable {
    MethodType mt = MethodType.methodType(String[].class, String[].class);
    MethodHandle mh = MethodHandles.publicLookup()
            .findStatic(THIS_CLASS, "f", mt);
    mh = MethodHandles.explicitCastArguments(mh,
            MethodType.methodType(Object.class, Object.class));
    mh.invokeWithArguments((Object) (new String[]{"str1", "str2"}));
}
 
Example 9
@Test
public void testVarargsList() throws Throwable {
    //System.out.println("varargsList");
    final int MIN = START_ARITY;
    final int MAX = MAX_ARITY-2;  // 253+1 would cause parameter overflow with 'this' added
    for (int nargs = MIN; nargs <= MAX; nargs = nextArgCount(nargs, 7, MAX)) {
        MethodHandle target = ValueConversions.varargsList(nargs);
        Object[] args = new Object[nargs];
        for (int i = 0; i < nargs; i++)
            args[i] = "#"+i;
        Object res = target.invokeWithArguments(args);
        assertEquals(Arrays.asList(args), res);
    }
}
 
Example 10
/**
 * Tests that MHs.eCA method works correctly with MHs with multiple arguments.
 * @throws Throwable
 */
public static void testMultipleArgs() throws Throwable {
    int arity = 1 + RNG.nextInt(Helper.MAX_ARITY / 2 - 2);
    int arityMinus = RNG.nextInt(arity);
    int arityPlus = arity + RNG.nextInt(Helper.MAX_ARITY / 2 - arity) + 1;
    MethodType mType = Helper.randomMethodTypeGenerator(arity);
    MethodType mTypeNew = Helper.randomMethodTypeGenerator(arity);
    MethodType mTypeNewMinus = Helper.randomMethodTypeGenerator(arityMinus);
    MethodType mTypeNewPlus = Helper.randomMethodTypeGenerator(arityPlus);
    Class<?> rType = mType.returnType();
    MethodHandle original;
    if (rType.equals(void.class)) {
        MethodType mt = MethodType.methodType(void.class);
        original = MethodHandles.publicLookup()
                .findStatic(THIS_CLASS, "retVoid", mt);
    } else {
        Object rValue = Helper.castToWrapper(1, rType);
        original = MethodHandles.constant(rType, rValue);
    }
    original = Helper.addTrailingArgs(original, arity, mType.parameterList());
    MethodHandle target = MethodHandles
                .explicitCastArguments(original, mTypeNew);
    Object[] parList = Helper.randomArgs(mTypeNew.parameterList());
    for (int i = 0; i < parList.length; i++) {
        if (parList[i] instanceof String) {
            parList[i] = null; //getting rid of Stings produced by randomArgs
        }
    }
    target.invokeWithArguments(parList);
    checkForWrongMethodTypeException(original, mTypeNewMinus);
    checkForWrongMethodTypeException(original, mTypeNewPlus);
}
 
Example 11
private void runTest() {
    if (Helper.IS_VERBOSE) {
        System.out.printf("CatchException(%s, isVararg=%b argsCount=%d "
                + "dropped=%d)%n",
                testCase, thrower.isVarargsCollector(),
                argsCount, dropped);
    }

    Helper.clear();

    Object[] args = Helper.randomArgs(
            argsCount, thrower.type().parameterArray());
    Object arg0 = Helper.MISSING_ARG;
    Object arg1 = testCase.thrown;
    if (argsCount > 0) {
        arg0 = args[0];
    }
    if (argsCount > 1) {
        args[1] = arg1;
    }
    Asserts.assertEQ(nargs, thrower.type().parameterCount());
    if (argsCount < nargs) {
        Object[] appendArgs = {arg0, arg1};
        appendArgs = Arrays.copyOfRange(appendArgs, argsCount, nargs);
        thrower = MethodHandles.insertArguments(
                thrower, argsCount, appendArgs);
    }
    Asserts.assertEQ(argsCount, thrower.type().parameterCount());

    MethodHandle target = MethodHandles.catchException(
            testCase.filter(thrower), testCase.throwableClass,
            testCase.filter(catcher));

    Asserts.assertEQ(thrower.type(), target.type());
    Asserts.assertEQ(argsCount, target.type().parameterCount());

    Object returned;
    try {
        returned = target.invokeWithArguments(args);
    } catch (Throwable ex) {
        if (CodeCacheOverflowProcessor.isThrowableCausedByVME(ex)) {
            // This error will be treated by CodeCacheOverflowProcessor
            // to prevent the test from failing because of code cache overflow.
            throw new Error(ex);
        }
        testCase.assertCatch(ex);
        returned = ex;
    }

    testCase.assertReturn(returned, arg0, arg1, dropped, args);
}
 
Example 12
Object construct(final ScriptFunction fn, final Object... arguments) throws Throwable {
    final MethodHandle mh   = getGenericConstructor(fn.getScope());
    final Object[]     args = arguments == null ? ScriptRuntime.EMPTY_ARRAY : arguments;

    DebuggerSupport.notifyInvoke(mh);

    if (isVarArg(mh)) {
        if (needsCallee(mh)) {
            return mh.invokeExact(fn, args);
        }
        return mh.invokeExact(args);
    }

    final int paramCount = mh.type().parameterCount();
    if (needsCallee(mh)) {
        switch (paramCount) {
        case 1:
            return mh.invokeExact(fn);
        case 2:
            return mh.invokeExact(fn, getArg(args, 0));
        case 3:
            return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1));
        case 4:
            return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1), getArg(args, 2));
        case 5:
            return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3));
        case 6:
            return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4));
        case 7:
            return mh.invokeExact(fn, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4), getArg(args, 5));
        default:
            return mh.invokeWithArguments(withArguments(fn, paramCount, args));
        }
    }

    switch (paramCount) {
    case 0:
        return mh.invokeExact();
    case 1:
        return mh.invokeExact(getArg(args, 0));
    case 2:
        return mh.invokeExact(getArg(args, 0), getArg(args, 1));
    case 3:
        return mh.invokeExact(getArg(args, 0), getArg(args, 1), getArg(args, 2));
    case 4:
        return mh.invokeExact(getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3));
    case 5:
        return mh.invokeExact(getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4));
    case 6:
        return mh.invokeExact(getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4), getArg(args, 5));
    default:
        return mh.invokeWithArguments(withArguments(null, paramCount, args));
    }
}
 
Example 13
public final Object dispatch(Object proxy, Method method, Object[] args, DefaultDispatch defaultDispatch) throws Throwable {
    final MethodHandle handle = boundMethodHandle(method);
    return handle == NULL_HANDLE ? defaultDispatch.call()
                                 : handle.invokeWithArguments(args);
}
 
Example 14
/**
 * Execute this script function.
 *
 * @param self  Target object.
 * @param arguments  Call arguments.
 * @return ScriptFunction result.
 *
 * @throws Throwable if there is an exception/error with the invocation or thrown from it
 */
Object invoke(final ScriptFunction fn, final Object self, final Object... arguments) throws Throwable {
    final MethodHandle mh      = getGenericInvoker(fn.getScope());
    final Object       selfObj = convertThisObject(self);
    final Object[]     args    = arguments == null ? ScriptRuntime.EMPTY_ARRAY : arguments;

    DebuggerSupport.notifyInvoke(mh);

    if (isVarArg(mh)) {
        if (needsCallee(mh)) {
            return mh.invokeExact(fn, selfObj, args);
        }
        return mh.invokeExact(selfObj, args);
    }

    final int paramCount = mh.type().parameterCount();
    if (needsCallee(mh)) {
        switch (paramCount) {
        case 2:
            return mh.invokeExact(fn, selfObj);
        case 3:
            return mh.invokeExact(fn, selfObj, getArg(args, 0));
        case 4:
            return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1));
        case 5:
            return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2));
        case 6:
            return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3));
        case 7:
            return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4));
        case 8:
            return mh.invokeExact(fn, selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4), getArg(args, 5));
        default:
            return mh.invokeWithArguments(withArguments(fn, selfObj, paramCount, args));
        }
    }

    switch (paramCount) {
    case 1:
        return mh.invokeExact(selfObj);
    case 2:
        return mh.invokeExact(selfObj, getArg(args, 0));
    case 3:
        return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1));
    case 4:
        return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2));
    case 5:
        return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3));
    case 6:
        return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4));
    case 7:
        return mh.invokeExact(selfObj, getArg(args, 0), getArg(args, 1), getArg(args, 2), getArg(args, 3), getArg(args, 4), getArg(args, 5));
    default:
        return mh.invokeWithArguments(withArguments(null, selfObj, paramCount, args));
    }
}
 
Example 15
@Test
public void testSpreads() throws Throwable {
    System.out.println("testing asSpreader on arity=3");
    Object[] args = testArgs(3);
    int r0 = Objects.hash(args);
    MethodHandle mh = MH_hashArguments(3);
    Object r;
    r = mh.invokeExact(args[0], args[1], args[2]);
    assertEquals(r0, r);
    r = mh.invoke(args[0], args[1], args[2]);
    assertEquals(r0, r);
    r = mh.invoke((Comparable) args[0], (Integer) args[1], (Number) args[2]);
    assertEquals(r0, r);
    r = mh.invokeWithArguments(args);
    assertEquals(r0, r);
    for (Class<?> cls0 : new Class<?>[] {
        Object[].class, Number[].class, Integer[].class, Comparable[].class
    }) {
        @SuppressWarnings("unchecked")
        Class<? extends Object[]> cls = (Class<? extends Object[]>) cls0;
        //Class<? extends Object[]> cls = Object[].class.asSubclass(cls0);
        int nargs = args.length, skip;
        MethodHandle smh = mh.asSpreader(cls, nargs - (skip = 0));
        Object[] tail = Arrays.copyOfRange(args, skip, nargs, cls);
        if (cls == Object[].class)
            r = smh.invokeExact(tail);
        else if (cls == Integer[].class)
            r = smh.invokeExact((Integer[]) tail); //warning OK, see 8019340
        else
            r = smh.invoke(tail);
        assertEquals(r0, r);
        smh = mh.asSpreader(cls, nargs - (skip = 1));
        tail = Arrays.copyOfRange(args, skip, nargs, cls);
        if (cls == Object[].class)
            r = smh.invokeExact(args[0], tail);
        else if (cls == Integer[].class)
            r = smh.invokeExact(args[0], (Integer[]) tail);
        else
            r = smh.invoke(args[0], tail);
        assertEquals(r0, r);
        smh = mh.asSpreader(cls, nargs - (skip = 2));
        tail = Arrays.copyOfRange(args, skip, nargs, cls);
        if (cls == Object[].class)
            r = smh.invokeExact(args[0], args[1], tail);
        else if (cls == Integer[].class)
            r = smh.invokeExact(args[0], args[1], (Integer[]) tail);
        else
            r = smh.invoke(args[0], args[1], tail);
        assertEquals(r0, r);
        smh = mh.asSpreader(cls, nargs - (skip = 3));
        tail = Arrays.copyOfRange(args, skip, nargs, cls);
        if (cls == Object[].class)
            r = smh.invokeExact(args[0], args[1], args[2], tail);
        else if (cls == Integer[].class)
            r = smh.invokeExact(args[0], args[1], args[2], (Integer[]) tail);
        else
            r = smh.invoke(args[0], args[1], args[2], tail);
        assertEquals(r0, r);
        // Try null array in addition to zero-length array:
        tail = null;
        if (cls == Object[].class)
            r = smh.invokeExact(args[0], args[1], args[2], tail);
        else if (cls == Integer[].class)
            r = smh.invokeExact(args[0], args[1], args[2], (Integer[]) tail);
        else
            r = smh.invoke(args[0], args[1], args[2], tail);
        assertEquals(r0, r);
    }
}
 
Example 16
/**
 * Trace event. Wrap an invocation with a return value
 *
 * @param mh     invocation handle
 * @param args   arguments to call
 *
 * @return return value from invocation
 *
 * @throws Throwable if invocation fails or throws exception/error
 */
@SuppressWarnings({"unused", "resource"})
public Object traceObject(final MethodHandle mh, final Object... args) throws Throwable {
    final PrintWriter out = Context.getCurrentErr();
    tracePrint(out, "ENTER ", args, null);
    final Object result = mh.invokeWithArguments(args);
    tracePrint(out, "EXIT  ", args, result);

    return result;
}
 
Example 17
/**
 * Trace event. Wrap an invocation with a return value
 *
 * @param mh     invocation handle
 * @param args   arguments to call
 *
 * @return return value from invocation
 *
 * @throws Throwable if invocation fails or throws exception/error
 */
@SuppressWarnings({"unused", "resource"})
public Object traceObject(final MethodHandle mh, final Object... args) throws Throwable {
    final PrintWriter out = Context.getCurrentErr();
    tracePrint(out, "ENTER ", args, null);
    final Object result = mh.invokeWithArguments(args);
    tracePrint(out, "EXIT  ", args, result);

    return result;
}
 
Example 18
/**
 * Trace event. Wrap an invocation with a return value
 *
 * @param mh     invocation handle
 * @param args   arguments to call
 *
 * @return return value from invocation
 *
 * @throws Throwable if invocation fails or throws exception/error
 */
@SuppressWarnings({"unused", "resource"})
public Object traceObject(final MethodHandle mh, final Object... args) throws Throwable {
    final PrintWriter out = Context.getCurrentErr();
    tracePrint(out, "ENTER ", args, null);
    final Object result = mh.invokeWithArguments(args);
    tracePrint(out, "EXIT  ", args, result);

    return result;
}
 
Example 19
/**
 * Trace event. Wrap an invocation that returns void
 *
 * @param mh     invocation handle
 * @param args   arguments to call
 *
 * @throws Throwable if invocation fails or throws exception/error
 */
@SuppressWarnings("unused")
public void traceVoid(final MethodHandle mh, final Object... args) throws Throwable {
    final PrintWriter out = Context.getCurrentErr();
    tracePrint(out, "ENTER ", args, null);
    mh.invokeWithArguments(args);
    tracePrint(out, "EXIT  ", args, null);
}
 
Example 20
/**
 * Trace event. Wrap an invocation with a return value
 *
 * @param mh     invocation handle
 * @param args   arguments to call
 *
 * @return return value from invocation
 *
 * @throws Throwable if invocation fails or throws exception/error
 */
@SuppressWarnings("unused")
public Object traceObject(final MethodHandle mh, final Object... args) throws Throwable {
    final PrintWriter out = Context.getCurrentErr();
    tracePrint(out, "ENTER ", args, null);
    final Object result = mh.invokeWithArguments(args);
    tracePrint(out, "EXIT  ", args, result);

    return result;
}