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

The following examples show how to use java.lang.invoke.MethodHandle#invoke() . 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: jdk8u60   File: InvokeMH.java    License: GNU General Public License v2.0 6 votes vote down vote up
void testGen(MethodHandle mh_SiO,
             MethodHandle mh_vS,
             MethodHandle mh_vi,
             MethodHandle mh_vv) throws Throwable {
    Object o; String s; int i;  // for return type testing

    // next five must have sig = (*,*)*
    o = mh_SiO.invoke((Object)"world", (Object)123);
    mh_SiO.invoke((Object)"mundus", (Object)456);
    Object k = "kosmos";
    o = mh_SiO.invoke(k, 789);
    o = mh_SiO.invoke(null, 000);
    o = mh_SiO.invoke("arda", -123);

    // sig = ()String
    o = mh_vS.invoke();

    // sig = ()int
    i = (int) mh_vi.invoke();
    o = (int) mh_vi.invoke();
    mh_vi.invoke();

    // sig = ()void
    mh_vv.invoke();
    o = mh_vv.invoke();
}
 
Example 2
@Test
@ParameterValueSource({"a", "1", "a1"})
@ParameterValueSource({"b", "3", "b3"})
@ParameterValueSource({"c", "7", "c7"})
@ParameterValueSource({"a", "15", "a15"})
@ParameterValueSource({"d", "9223372036854775807", "d9223372036854775807"}) // Long.MAX_VALUE
@ParameterValueSource({"e", "-9223372036854775808", "e-9223372036854775808"}) // Long.MIN_VALUE
public void twoConcatWithPrimitives_StringAndLong(
    @RuntimeMethodHandle(
            className = "StringConcatTestCases",
            memberName = "twoConcatWithPrimitives",
            memberDescriptor = "(Ljava/lang/String;J)Ljava/lang/String;")
        MethodHandle twoConcat,
    @FromParameterValueSource String x,
    @FromParameterValueSource long y,
    @FromParameterValueSource String expectedResult)
    throws Throwable {
  String result = (String) twoConcat.invoke(x, y);
  assertThat(result).isEqualTo(expectedResult);
}
 
Example 3
@Test
public void testReturnFromArg() throws Throwable {
    MethodHandles.Lookup l = MethodHandles.lookup();

    MethodHandle consumeIdentity = dropArguments(
            identity(String.class), 1, int.class, int.class);
    MethodHandle consumeVoid = l.findStatic(
            PermuteArgsReturnVoidTest.class, "consumeVoid",
            MethodType.methodType(void.class, String.class, int.class, int.class));

    MethodHandle f = MethodHandles.foldArguments(consumeIdentity, consumeVoid);

    MethodHandle p = MethodHandles.permuteArguments(f, MethodType.methodType(String.class, String.class, int.class, int.class), 0, 2, 1);

    String s = (String) p.invoke("IN", 0, 0);
    Assert.assertEquals(s.getClass(), String.class);
    Assert.assertEquals(s, "IN");
}
 
Example 4
@Test(dataProvider = "versions")
public void test(String version, int expected) throws Throwable {
    StandardJavaFileManager jfm = ToolProvider.getSystemJavaCompiler().getStandardFileManager(null, null, null);
    jfm.setLocation(jloc, List.of(new File("multi-release.jar")));

    if (version.length() > 0) {
        jfm.handleOption("--multi-release", List.of(version).iterator());
    }

    CustomClassLoader cldr = new CustomClassLoader(jfm);
    Class<?> versionClass = cldr.loadClass("version.Version");
    MethodType mt = MethodType.methodType(int.class);
    MethodHandle mh = MethodHandles.lookup().findVirtual(versionClass, "getVersion", mt);
    int v = (int)mh.invoke(versionClass.newInstance());
    Assert.assertEquals(v, expected);

    jfm.close();
}
 
Example 5
Source Project: AVM   File: ReflectionBenchmarkSameAccessTest.java    License: MIT License 6 votes vote down vote up
private long sameInstanceMethodHandleConstructorAccessInvokeOnly(int spins) throws Throwable {
    MethodHandle constructor = MethodHandles.lookup().findConstructor(ReflectionTarget.class, MethodType.methodType(
        void.class,
        String.class,
        Object.class,
        Character.class,
        Float[].class));
    String string = ReflectionBenchmarkConstants.constructorArg1;
    Object object = ReflectionBenchmarkConstants.constructorArg2;
    Character character = ReflectionBenchmarkConstants.constructorArg3;
    Float[] floats = ReflectionBenchmarkConstants.constructorArg4;

    long start = System.nanoTime();
    for (int i = 0; i < spins; i++) {
        constructor.invoke(string, object, character, floats);
    }
    long end = System.nanoTime();
    return end - start;
}
 
Example 6
@Test
public void testInstanceOfReceiverClassVarargs() throws Throwable {
    try {
        MethodHandle bound = lookup().bind(new pkg.A(), "m3", MethodType.methodType(String.class, String[].class));
        bound.invoke();
        fail("IllegalAccessException expected");
    } catch (IllegalAccessException e) {
    }
}
 
Example 7
@Test
public void executeUserApp_invokeStaticMethodDesugarTwice(
    @RuntimeMethodHandle(
            className = "com.app.testing.CuboidCalculator",
            memberName = "invokeStaticMethod",
            round = 2)
        MethodHandle method)
    throws Throwable {
  long result = (long) method.invoke(2L, 3L, 4L, 10L, 10L, 10L);
  assertThat(result).isEqualTo(24000L);
}
 
Example 8
Source Project: bazel   File: NioBufferRefConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void methodOfNioBufferWithCovariantTypes_afterDesugarInvocationOfByteBufferMethod(
    @RuntimeMethodHandle(className = "NioBufferInvocations", memberName = "getByteBufferPosition")
        MethodHandle after)
    throws Throwable {
  ByteBuffer buffer = ByteBuffer.wrap("random text".getBytes(Charset.defaultCharset()));
  int expectedPos = 2;

  ByteBuffer result = (ByteBuffer) after.invoke(buffer, expectedPos);
  assertThat(result.position()).isEqualTo(expectedPos);
}
 
Example 9
Source Project: AVM   File: ReflectionBenchmarkSameAccessTest.java    License: MIT License 5 votes vote down vote up
private long sameInstanceMethodHandleInstanceFieldWriteInline(int spins) throws Throwable {
    MethodHandle constructor = MethodHandles.lookup().findConstructor(
        ReflectionTarget.class,
        MethodType.methodType(void.class));
    ReflectionTarget target = (ReflectionTarget) constructor.invoke();
    Object object = new Object();

    long start = System.nanoTime();
    for (int i = 0; i < spins; i++) {
        INSTANCE_FIELD_WRITE.invokeExact(target, object);
    }
    long end = System.nanoTime();
    return end - start;
}
 
Example 10
@Test
public void executeUserApp_invokeDerivedClassConstructorWithEmbeddedInstanceDesugarOnce(
    @RuntimeMethodHandle(
            className = "com.app.testing.CuboidCalculator",
            memberName = "invokeDerivedClassConstructorWithEmbeddedInstance",
            round = 1)
        MethodHandle method)
    throws Throwable {
  long result = (long) method.invoke(2L, 3L, 4L);
  assertThat(result).isEqualTo(24L);
}
 
Example 11
@Test
public void comprehensiveTest(
    @RuntimeMethodHandle(className = "Xylem", memberName = "execute") MethodHandle xylemExecute)
    throws Throwable {
  long result = (long) xylemExecute.invoke((long) 2L, (int) 3);
  assertThat(result).isEqualTo(14004004171L);
}
 
Example 12
public static boolean executeMethod(String mName, CommandControl inst) throws Throwable {
    MethodHandle handle = getHandle(mName);
    if (handle != null) {
        handle.invoke(CACHE_CLASS.get(handle).getConstructor(
                CommandControl.class).newInstance(inst));
        
        return true;
    }
    return false;
}
 
Example 13
@Test
public void twoConcat_StringAndObject(
    @RuntimeMethodHandle(
            className = "StringConcatTestCases",
            memberName = "twoConcat",
            memberDescriptor = "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;")
        MethodHandle twoConcat)
    throws Throwable {
  String result = (String) twoConcat.invoke("ab", (Object) "cd");
  assertThat(result).isEqualTo("T:abcd");
}
 
Example 14
Source Project: presto   File: RowEqualOperator.java    License: Apache License 2.0 5 votes vote down vote up
public static Boolean equals(RowType rowType, List<MethodHandle> fieldEqualOperators, Block leftRow, Block rightRow)
{
    boolean indeterminate = false;
    for (int fieldIndex = 0; fieldIndex < leftRow.getPositionCount(); fieldIndex++) {
        if (leftRow.isNull(fieldIndex) || rightRow.isNull(fieldIndex)) {
            indeterminate = true;
            continue;
        }
        Type fieldType = rowType.getTypeParameters().get(fieldIndex);
        Object leftField = readNativeValue(fieldType, leftRow, fieldIndex);
        Object rightField = readNativeValue(fieldType, rightRow, fieldIndex);
        try {
            MethodHandle equalOperator = fieldEqualOperators.get(fieldIndex);
            Boolean result = (Boolean) equalOperator.invoke(leftField, rightField);
            if (result == null) {
                indeterminate = true;
            }
            else if (!result) {
                return false;
            }
        }
        catch (Throwable t) {
            throw internalError(t);
        }
    }

    if (indeterminate) {
        return null;
    }
    return true;
}
 
Example 15
@Test
public static void testCountedPrintingLoop() throws Throwable {
    MethodHandle fit5 = MethodHandles.constant(int.class, 5);
    MethodHandle loop = MethodHandles.countedLoop(fit5, null, Counted.MH_printHello);
    assertEquals(Counted.MT_countedPrinting, loop.type());
    loop.invoke();
}
 
Example 16
@Test(dataProvider = "testCasesAll",
        dataProviderClass = DefaultStaticTestData.class)
public void testMethodHandleInvoke(String testTarget, Object param)
        throws Throwable {
    Class<?> typeUnderTest = Class.forName(testTarget);
    MethodDesc[] expectedMethods = typeUnderTest.getAnnotationsByType(MethodDesc.class);

    for (MethodDesc toTest : expectedMethods) {
        String mName = toTest.name();
        Mod mod = toTest.mod();
        if (mod != STATIC && typeUnderTest.isInterface()) {
            return;
        }

        String result = null;
        String expectedReturn = toTest.retval();

        MethodHandle methodHandle = getTestMH(typeUnderTest, mName, param);
        if (mName.equals("staticMethod")) {
            result = (param == null)
                    ? (String) methodHandle.invoke()
                    : (String) methodHandle.invoke(param);
        } else {
            result = (param == null)
                    ? (String) methodHandle.invoke(typeUnderTest.newInstance())
                    : (String) methodHandle.invoke(typeUnderTest.newInstance(), param);
        }

        assertEquals(result, expectedReturn);
    }

}
 
Example 17
Source Project: sofa-jraft   File: ProtobufMsgFactory.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends Message> T newMessageByProtoClassName(final String className, final byte[] bs) {
    final MethodHandle handle = PARSE_METHODS_4PROTO.get(className);
    if (handle == null) {
        throw new MessageClassNotFoundException(className + " not found");
    }
    try {
        return (T) handle.invoke(bs);
    } catch (Throwable t) {
        throw new SerializationException(t);
    }
}
 
Example 18
@Test
public void testFindSpecial() throws Throwable {
    MethodHandles.Lookup lookup = (MethodHandles.Lookup)t3.getDeclaredMethod("getLookup").invoke(null);
    MethodHandle mh = lookup.findSpecial(t1, "m", MethodType.methodType(int.class), t3);
    int result = (int)mh.invoke(t3.newInstance());
    assertEquals(result, 1); // T1.m should be invoked.
}
 
Example 19
@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 20
Source Project: gravel   File: MethodTools.java    License: Apache License 2.0 4 votes vote down vote up
public static Object perform(Object receiver, String selector, Object arg1)
		throws Throwable {
	MethodHandle handle = getHandle(receiver, selector);
	return handle.invoke(receiver, arg1);
}