Java Code Examples for java.lang.invoke.MethodHandle

The following examples show how to use java.lang.invoke.MethodHandle. 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
/**
 * Return element getter for a {@link ContinuousArrayData}
 * @param clazz        clazz for exact type guard
 * @param getHas       has getter
 * @param returnType   return type
 * @param programPoint program point
 * @return method handle for element setter
 */
protected MethodHandle getContinuousElementGetter(final Class<? extends ContinuousArrayData> clazz, final MethodHandle getHas, final Class<?> returnType, final int programPoint) {
    final boolean isOptimistic = isValid(programPoint);
    final int     fti          = getAccessorTypeIndex(getHas.type().returnType());
    final int     ti           = getAccessorTypeIndex(returnType);
    MethodHandle  mh           = getHas;

    if (isOptimistic) {
        if (ti < fti) {
            mh = MH.insertArguments(ArrayData.THROW_UNWARRANTED.methodHandle(), 1, programPoint);
        }
    }
    mh = MH.asType(mh, mh.type().changeReturnType(returnType).changeParameterType(0, clazz));

    if (!isOptimistic) {
        //for example a & array[17];
        return Lookup.filterReturnType(mh, returnType);
    }
    return mh;
}
 
Example 2
public static MethodHandle boxExact(Wrapper wrap) {
    WrapperCache cache = BOX_CONVERSIONS[0];
    MethodHandle mh = cache.get(wrap);
    if (mh != null) {
        return mh;
    }
    // look up the method
    String name = "box" + wrap.wrapperSimpleName();
    MethodType type = boxType(wrap);
    try {
        mh = IMPL_LOOKUP.findStatic(THIS_CLASS, name, type);
    } catch (ReflectiveOperationException ex) {
        mh = null;
    }
    if (mh != null) {
        return cache.put(wrap, mh);
    }
    throw new IllegalArgumentException("cannot find box adapter for " + wrap);
}
 
Example 3
@Test
public void testCast() throws Throwable {
    //System.out.println("cast");
    Class<?>[] types = { Object.class, Serializable.class, String.class, Number.class, Integer.class };
    Object[] objects = { new Object(), Boolean.FALSE,      "hello",      (Long)12L,    (Integer)6    };
    for (Class<?> dst : types) {
        MethodHandle caster = ValueConversions.cast(dst);
        assertEquals(caster.type(), ValueConversions.identity().type());
        for (Object obj : objects) {
            Class<?> src = obj.getClass();
            boolean canCast = dst.isAssignableFrom(src);
            //System.out.println("obj="+obj+" <: dst="+dst+(canCast ? " (OK)" : " (will fail)"));
            try {
                Object result = caster.invokeExact(obj);
                if (canCast)
                    assertEquals(obj, result);
                else
                    assertEquals("cast should not have succeeded", dst, obj);
            } catch (ClassCastException ex) {
                if (canCast)
                    throw ex;
            }
        }
    }
}
 
Example 4
Source Project: openjdk-jdk9   Source File: CallSiteTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInitialize() {
    final DynamicLinkerFactory factory = new DynamicLinkerFactory();
    final DynamicLinker linker = factory.createLinker();
    final MethodType mt = MethodType.methodType(Object.class, Object.class);
    final boolean[] initializeCalled = { Boolean.FALSE };
    linker.link(new SimpleRelinkableCallSite(new CallSiteDescriptor(
        MethodHandles.publicLookup(), GET_PROPERTY.named("DO_NOT_CARE"), mt)) {
            @Override
            public void initialize(final MethodHandle relinkAndInvoke) {
                initializeCalled[0] = Boolean.TRUE;
                super.initialize(relinkAndInvoke);
            }
        });

    Assert.assertTrue(initializeCalled[0]);
}
 
Example 5
@SuppressWarnings("unused")
private static boolean knownFunctionPropertyGuardProto(final Object self, final PropertyMap map, final MethodHandle getter, final int depth, final ScriptFunction func) {
    if (self instanceof ScriptObject && ((ScriptObject)self).getMap() == map) {
        final ScriptObject proto = getProto((ScriptObject)self, depth);
        if (proto == null) {
            return false;
        }
        try {
            return getter.invokeExact((Object)proto) == func;
        } catch (final RuntimeException | Error e) {
            throw e;
        } catch (final Throwable t) {
            throw new RuntimeException(t);
        }
    }

    return false;
}
 
Example 6
/**
 * If we are setting boxed types (because the compiler couldn't determine which they were) to
 * a primitive field, we can reuse the primitive field getter, as long as we are setting an element
 * of the same boxed type as the primitive type representation
 *
 * @param forType           the current type
 * @param primitiveSetter   primitive setter for the current type with an element of the current type
 * @param objectSetter      the object setter
 *
 * @return method handle that checks if the element to be set is of the current type, even though it's boxed
 *  and instead of using the generic object setter, that would blow up the type and invalidate the map,
 *  unbox it and call the primitive setter instead
 */
public static MethodHandle createGuardBoxedPrimitiveSetter(final Class<?> forType, final MethodHandle primitiveSetter, final MethodHandle objectSetter) {
    final Class<? extends Number> boxedForType = getBoxedType(forType);
    //object setter that checks for primitive if current type is primitive
    return MH.guardWithTest(
        MH.insertArguments(
            MH.dropArguments(
                IS_TYPE_GUARD,
                1,
                Object.class),
            0,
            boxedForType),
            MH.asType(
                primitiveSetter,
                objectSetter.type()),
            objectSetter);
}
 
Example 7
Source Project: Diorite   Source File: ConstructorInvoker.java    License: MIT License 6 votes vote down vote up
@Override
public MethodHandle getHandle()
{
    if (this.cached != null)
    {
        return this.cached;
    }
    try
    {
        return this.cached = MethodHandles.lookup().unreflectConstructor(this.constructor);
    }
    catch (IllegalAccessException e)
    {
        throw new RuntimeException("Cannot access reflection.", e);
    }
}
 
Example 8
Source Project: TencentKona-8   Source File: SpillProperty.java    License: GNU General Public License v2.0 6 votes vote down vote up
MethodHandle getOrCreate(final boolean isPrimitive, final boolean isGetter) {
    MethodHandle accessor;

    accessor = getInner(isPrimitive, isGetter);
    if (accessor != null) {
        return accessor;
    }

    accessor = primordial(isPrimitive, isGetter);
    accessor = MH.insertArguments(accessor, 1, slot);
    if (!isGetter) {
        accessor = MH.filterArguments(accessor, 0, ensureSpillSize);
    }
    setInner(isPrimitive, isGetter, accessor);

    return accessor;
}
 
Example 9
Source Project: vividus   Source File: FluentTrimmedEnumConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<MethodHandle> load(Class<?> clazz) throws Exception
{
    try
    {
        MethodType mt = MethodType.methodType(clazz, String.class);
        MethodHandle fromString = MethodHandles.publicLookup().findStatic(clazz, "fromString", mt);
        return Optional.of(fromString);
    }
    catch (NoSuchMethodException | SecurityException | IllegalAccessException e)
    {
        return Optional.empty();
    }
}
 
Example 10
private static Callable<MethodHandle> invokerCreator(final Class<?> rtype, final Class<?>... ptypes) {
    return new Callable<MethodHandle>() {
        @Override
        public MethodHandle call() {
            return Bootstrap.createDynamicInvoker("dyn:call", rtype, ptypes);
        }
    };
}
 
Example 11
Source Project: presto   Source File: ArrayMaxFunction.java    License: Apache License 2.0 5 votes vote down vote up
@TypeParameter("T")
@SqlType("T")
@SqlNullable
public static Block blockArrayMax(
        @OperatorDependency(operator = GREATER_THAN, argumentTypes = {"T", "T"}) MethodHandle compareMethodHandle,
        @TypeParameter("T") Type elementType,
        @SqlType("array(T)") Block block)
{
    try {
        if (block.getPositionCount() == 0) {
            return null;
        }

        Block selectedValue = (Block) elementType.getObject(block, 0);
        for (int i = 0; i < block.getPositionCount(); i++) {
            if (block.isNull(i)) {
                return null;
            }
            Block value = (Block) elementType.getObject(block, i);
            if ((boolean) compareMethodHandle.invokeExact(value, selectedValue)) {
                selectedValue = value;
            }
        }

        return selectedValue;
    }
    catch (Throwable t) {
        throw internalError(t);
    }
}
 
Example 12
Source Project: jdk8u_jdk   Source File: TestPrivateMember.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void test() throws Throwable {
    MethodHandles.Lookup lookup = MethodHandles.lookup();
    MethodType mt = MethodType.methodType(void.class);
    try {
        Class<?> checkInittedHolder = TestPrivateMemberPackageSibling.class;
        // Original model:  checkInittedHolder = Class.class;
        // Not using Class.checkInitted because it could change without notice.
        MethodHandle mh = lookup.findStatic(checkInittedHolder, "checkInitted", mt);
        throw new RuntimeException("IllegalAccessException not thrown");
    } catch (IllegalAccessException e) {
        // okay
        System.out.println("Expected exception: " + e.getMessage());
    }
}
 
Example 13
@Override
Map<String, MethodHandle> getInnerClassGetters() {
    final Map<String, MethodHandle> map = new HashMap<>();
    for(final Class<?> innerClass: membersLookup.getInnerClasses()) {
        map.put(innerClass.getSimpleName(), editMethodHandle(MethodHandles.constant(StaticClass.class,
                StaticClass.forClass(innerClass))));
    }
    return map;
}
 
Example 14
@Override
public MethodHandle findStatic(final MethodHandles.Lookup explicitLookup, final Class<?> clazz, final String name, final MethodType type) {
    try {
        final MethodHandle mh = explicitLookup.findStatic(clazz, name, type);
        return debug(mh, "findStatic", explicitLookup, clazz, name, type);
    } catch (final NoSuchMethodException | IllegalAccessException e) {
        throw new LookupException(e);
    }
}
 
Example 15
@Test
public static void testWhileZip() throws Throwable {
    MethodHandle loop = MethodHandles.doWhileLoop(While.MH_zipInitZip, While.MH_zipStep, While.MH_zipPred);
    assertEquals(While.MT_zip, loop.type());
    List<String> a = Arrays.asList("a", "b", "c", "d");
    List<String> b = Arrays.asList("e", "f", "g", "h");
    List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
    assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
}
 
Example 16
public void testDirectStdSer() throws Throwable {
    MethodHandle fooMH = MethodHandles.lookup().findStatic(SerializedLambdaTest.class, "foo", predicateMT);

    // Standard metafactory, serializable target: not serializable
    CallSite cs = LambdaMetafactory.metafactory(MethodHandles.lookup(),
                                                "test", MethodType.methodType(SerPredicate.class),
                                                predicateMT, fooMH, stringPredicateMT);
    assertNotSerial((SerPredicate<String>) cs.getTarget().invokeExact(), fooAsserter);
}
 
Example 17
static void testConvert(Wrapper src, Wrapper dst, long tval) throws Throwable {
    if (dst == Wrapper.OBJECT || src == Wrapper.OBJECT)  return;  // must have prims
    if (dst == Wrapper.VOID   || src == Wrapper.VOID  )  return;  // must have values
    boolean testSingleCase = (tval != 0);
    final long tvalInit = tval;
    MethodHandle conv = ValueConversions.convertPrimitive(src, dst);
    MethodType convType = MethodType.methodType(dst.primitiveType(), src.primitiveType());
    assertEquals(convType, conv.type());
    MethodHandle converter = conv.asType(conv.type().changeReturnType(Object.class));
    for (;;) {
        long n = tval;
        Object testValue = src.wrap(n);
        Object expResult = dst.cast(testValue, dst.primitiveType());
        Object result;
        switch (src) {
            case INT:     result = converter.invokeExact((int)n); break;
            case LONG:    result = converter.invokeExact(/*long*/n); break;
            case FLOAT:   result = converter.invokeExact((float)n); break;
            case DOUBLE:  result = converter.invokeExact((double)n); break;
            case CHAR:    result = converter.invokeExact((char)n); break;
            case BYTE:    result = converter.invokeExact((byte)n); break;
            case SHORT:   result = converter.invokeExact((short)n); break;
            case BOOLEAN: result = converter.invokeExact((n & 1) != 0); break;
            default:  throw new AssertionError();
        }
        assertEquals("(src,dst,n,testValue)="+Arrays.asList(src,dst,"0x"+Long.toHexString(n),testValue),
                     expResult, result);
        if (testSingleCase)  break;
        // next test value:
        tval = nextTestValue(tval);
        if (tval == tvalInit)  break;  // repeat
    }
}
 
Example 18
Source Project: TencentKona-8   Source File: NativeRegExp.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static final MethodHandle getReplaceValueInvoker() {
    return Global.instance().getDynamicInvoker(REPLACE_VALUE,
            new Callable<MethodHandle>() {
                @Override
                public MethodHandle call() {
                    return Bootstrap.createDynamicInvoker("dyn:call",
                        String.class, Object.class, Object.class, Object[].class);
                }
            });
}
 
Example 19
Source Project: snowcast   Source File: NodeSequencerService.java    License: Apache License 2.0 5 votes vote down vote up
private MethodHandle hz37EventRegistrationGetListener(BuildInfo buildInfo) {
    //ACCESSIBILITY_HACK
    return execute(() -> {
        Class<?> clazz = Class.forName("com.hazelcast.spi.impl.eventservice.impl.Registration");
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        return lookup.findVirtual(clazz, "getListener", GET_LISTENER_GET_TYPE);
    }, INTERNAL_SETUP_FAILED, exceptionParameters(buildInfo.getVersion()));
}
 
Example 20
private static MethodHandle dropReceiver(final MethodHandle mh, final Class<?> receiverClass) {
    MethodHandle newHandle = MethodHandles.dropArguments(mh, 0, receiverClass);
    // NOTE: this is a workaround for the fact that dropArguments doesn't preserve vararg collector state.
    if(mh.isVarargsCollector() && !newHandle.isVarargsCollector()) {
        final MethodType type = mh.type();
        newHandle = newHandle.asVarargsCollector(type.parameterType(type.parameterCount() - 1));
    }
    return newHandle;
}
 
Example 21
Source Project: bazel   Source File: IndyStringConcatDesugaringlTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void twoConcatWithPrimitives_longAndString(
    @RuntimeMethodHandle(
            className = "StringConcatTestCases",
            memberName = "twoConcatWithPrimitives",
            memberDescriptor = "(JLjava/lang/String;)Ljava/lang/String;")
        MethodHandle twoConcat)
    throws Throwable {
  String result = (String) twoConcat.invoke(123L, "ABC");
  assertThat(result).isEqualTo("123ABC");
}
 
Example 22
Source Project: jdk8u60   Source File: NativeRegExp.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static final MethodHandle getReplaceValueInvoker() {
    return Global.instance().getDynamicInvoker(REPLACE_VALUE,
            new Callable<MethodHandle>() {
                @Override
                public MethodHandle call() {
                    return Bootstrap.createDynamicInvoker("dyn:call", String.class, ScriptFunction.class, Object.class, Object[].class);
                }
            });
}
 
Example 23
Source Project: es6draft   Source File: Bootstrap.java    License: MIT License 5 votes vote down vote up
private static MethodHandle addSetup(MutableCallSite callsite, Object arg1, Object arg2, ExecutionContext cx) {
    Type type = getType(arg1, arg2);
    MethodHandle target;
    if (type == Type.String) {
        target = addStringMH;
    } else if (type == Type.Number) {
        target = addNumberMH;
    } else {
        target = null;
    }
    return setCallSiteTarget(callsite, target, getTestForBinary(type), addGenericMH);
}
 
Example 24
public static MethodHandle convertPrimitive(Wrapper wsrc, Wrapper wdst) {
    EnumMap<Wrapper, MethodHandle> cache = CONVERT_PRIMITIVE_FUNCTIONS[wsrc.ordinal()];
    MethodHandle mh = cache.get(wdst);
    if (mh != null) {
        return mh;
    }
    // slow path
    Class<?> src = wsrc.primitiveType();
    Class<?> dst = wdst.primitiveType();
    MethodType type = src == void.class ? MethodType.methodType(dst) : MethodType.methodType(dst, src);
    if (wsrc == wdst) {
        mh = identity(src);
    } else if (wsrc == Wrapper.VOID) {
        mh = zeroConstantFunction(wdst);
    } else if (wdst == Wrapper.VOID) {
        mh = MethodHandles.dropArguments(EMPTY, 0, src);  // Defer back to MethodHandles.
    } else if (wsrc == Wrapper.OBJECT) {
        mh = unboxCast(dst);
    } else if (wdst == Wrapper.OBJECT) {
        mh = box(src);
    } else {
        assert(src.isPrimitive() && dst.isPrimitive());
        try {
            mh = IMPL_LOOKUP.findStatic(THIS_CLASS, src.getSimpleName()+"To"+capitalize(dst.getSimpleName()), type);
        } catch (ReflectiveOperationException ex) {
            mh = null;
        }
    }
    if (mh != null) {
        assert(mh.type() == type) : mh;
        cache.put(wdst, mh);
        return mh;
    }

    throw new IllegalArgumentException("cannot find primitive conversion function for " +
                                       src.getSimpleName()+" -> "+dst.getSimpleName());
}
 
Example 25
Source Project: nashorn   Source File: ClassString.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if the supplied method is applicable to actual parameter classes represented by this ClassString
 * object.
 *
 */
private boolean isApplicable(MethodHandle method, LinkerServices linkerServices, boolean varArg) {
    final Class<?>[] formalTypes = method.type().parameterArray();
    final int cl = classes.length;
    final int fl = formalTypes.length - (varArg ? 1 : 0);
    if(varArg) {
        if(cl < fl) {
            return false;
        }
    } else {
        if(cl != fl) {
            return false;
        }
    }
    // Starting from 1 as we ignore the receiver type
    for(int i = 1; i < fl; ++i) {
        if(!canConvert(linkerServices, classes[i], formalTypes[i])) {
            return false;
        }
    }
    if(varArg) {
        final Class<?> varArgType = formalTypes[fl].getComponentType();
        for(int i = fl; i < cl; ++i) {
            if(!canConvert(linkerServices, classes[i], varArgType)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 26
Source Project: hottub   Source File: CompiledFunction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a guarded invocation for this function when not invoked as a constructor. The guarded invocation has no
 * guard but it potentially has an optimistic assumptions switch point. As such, it will probably not be used as a
 * final guarded invocation, but rather as a holder for an invocation handle and switch point to be decomposed and
 * reassembled into a different final invocation by the user of this method. Any recompositions should take care to
 * continue to use the switch point. If that is not possible, use {@link #createComposableInvoker()} instead.
 * @return a guarded invocation for an ordinary (non-constructor) invocation of this function.
 */
GuardedInvocation createFunctionInvocation(final Class<?> callSiteReturnType, final int callerProgramPoint) {
    return getValidOptimisticInvocation(new Supplier<MethodHandle>() {
        @Override
        public MethodHandle get() {
            return createInvoker(callSiteReturnType, callerProgramPoint);
        }
    }).createInvocation();
}
 
Example 27
static MethodHandle getINVOKE_UA_GETTER(final Class<?> returnType, final int programPoint) {
    if (UnwarrantedOptimismException.isValid(programPoint)) {
        final int flags = NashornCallSiteDescriptor.CALLSITE_OPTIMISTIC | programPoint << CALLSITE_PROGRAM_POINT_SHIFT;
        return Bootstrap.createDynamicInvoker("dyn:call", flags, returnType, Object.class, Object.class);
    } else {
        return Bootstrap.createDynamicInvoker("dyn:call", Object.class, Object.class, Object.class);
    }
}
 
Example 28
/**
 * Returns a direct MethodHandle for the {@code writeReplace} method on
 * a serializable class.
 * The single argument of {@link MethodHandle#invoke} is the serializable
 * object.
 *
 * @param cl the Serializable class
 * @return  a direct MethodHandle for the {@code writeReplace} method of the class or
 *          {@code null} if the class does not have a {@code writeReplace} method
 */
private MethodHandle getReplaceResolveForSerialization(Class<?> cl,
                                                       String methodName) {
    if (!Serializable.class.isAssignableFrom(cl)) {
        return null;
    }

    Class<?> defCl = cl;
    while (defCl != null) {
        try {
            Method m = defCl.getDeclaredMethod(methodName);
            if (m.getReturnType() != Object.class) {
                return null;
            }
            int mods = m.getModifiers();
            if (Modifier.isStatic(mods) | Modifier.isAbstract(mods)) {
                return null;
            } else if (Modifier.isPublic(mods) | Modifier.isProtected(mods)) {
                // fall through
            } else if (Modifier.isPrivate(mods) && (cl != defCl)) {
                return null;
            } else if (!packageEquals(cl, defCl)) {
                return null;
            }
            try {
                // Normal return
                m.setAccessible(true);
                return MethodHandles.lookup().unreflect(m);
            } catch (IllegalAccessException ex0) {
                // setAccessible should prevent IAE
                throw new InternalError("Error", ex0);
            }
        } catch (NoSuchMethodException ex) {
            defCl = defCl.getSuperclass();
        }
    }
    return null;
}
 
Example 29
@Override
public MethodHandle find(final Method method) {
    try {
        return PUBLIC_LOOKUP.unreflect(method);
    } catch (final IllegalAccessException e) {
        throw new LookupException(e);
    }
}
 
Example 30
@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);
    }

}