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

The following examples show how to use java.lang.invoke.MethodHandle#asType() . 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
private static void test(String pkg) throws Throwable {
    byte[] bytes = dumpClass(pkg);
    // Define VM anonymous class in privileged context (on BCP).
    Class anonClass = unsafe.defineAnonymousClass(Object.class, bytes, null);

    MethodType t = MethodType.methodType(Object.class, int.class);
    MethodHandle target = MethodHandles.lookup().findStatic(anonClass, "get", t);

    // Wrap target into LF (convert) to get "target" referenced from LF
    MethodHandle wrappedMH = target.asType(MethodType.methodType(Object.class, Integer.class));

    // Invoke enough times to provoke LF compilation to bytecode.
    for (int i = 0; i<100; i++) {
        Object r = wrappedMH.invokeExact((Integer)1);
    }
}
 
Example 2
private MethodHandle introspectConstructor()
{
  try {
    Method m = _type.getMethod("valueOf", String.class);
    
    Objects.requireNonNull(m);
    
    m.setAccessible(true);
      
    MethodHandle mh = MethodHandles.lookup().unreflect(m);
        
    mh = mh.asType(MethodType.methodType(Object.class, String.class));
      
    return mh;
  } catch (Exception e) {
    throw new H3ExceptionIn(_type.getName() + ": " + e.getMessage(), e);
  }
}
 
Example 3
private static void test(String pkg) throws Throwable {
    byte[] bytes = dumpClass(pkg);
    // Define VM anonymous class in privileged context (on BCP).
    Class anonClass = unsafe.defineAnonymousClass(Object.class, bytes, null);

    MethodType t = MethodType.methodType(Object.class, int.class);
    MethodHandle target = MethodHandles.lookup().findStatic(anonClass, "get", t);

    // Wrap target into LF (convert) to get "target" referenced from LF
    MethodHandle wrappedMH = target.asType(MethodType.methodType(Object.class, Integer.class));

    // Invoke enough times to provoke LF compilation to bytecode.
    for (int i = 0; i<100; i++) {
        Object r = wrappedMH.invokeExact((Integer)1);
    }
}
 
Example 4
public FieldFloat(Field field)
{
  super(field);
  
  try {
    MethodHandle getter = MethodHandles.lookup().unreflectGetter(field);
    _getter = getter.asType(MethodType.methodType(float.class, Object.class));
  
    MethodHandle setter = MethodHandles.lookup().unreflectSetter(field);
    _setter = setter.asType(MethodType.methodType(void.class, Object.class, float.class));
  } catch (Exception e) {
    throw new IllegalStateException(e);
  }
}
 
Example 5
Source Project: gravel   File: BaseCallSite.java    License: Apache License 2.0 5 votes vote down vote up
private MethodHandle getFallbackMethod() {
	try {
		final MethodType fallbackType = MethodType.genericMethodType(
				type.parameterCount()).insertParameterTypes(0,
				BaseCallSite.class);
		final MethodHandle fallbackHandle = MethodHandles.insertArguments(
				MethodHandles.lookup().findStatic(BaseCallSite.class,
						"invocationFallback", fallbackType), 0, this);
		return fallbackHandle.asType(type);
	} catch (NoSuchMethodException | IllegalAccessException e) {
		throw new RuntimeException(e);
	}
}
 
Example 6
public static MethodHandle cast(MethodHandle mh, MethodType mt) throws Throwable {
	println("calling " + mh.type() + " as " + mt);
	if (explicit) {
		return MethodHandles.explicitCastArguments(mh, mt);
	} else {
		return mh.asType(mt);
	}
}
 
Example 7
Source Project: proxy2   File: RetroRT.java    License: Apache License 2.0 5 votes vote down vote up
public static CallSite metafactory(Lookup lookup, String name, MethodType type,
                                   MethodType sig, MethodHandle impl, MethodType reifiedSig) throws Throwable {
  Class<?>[] capturedTypes = type.parameterArray();
  MethodHandle target = impl.asType(reifiedSig.insertParameterTypes(0, capturedTypes)); // apply generic casts
  MethodHandle mh = Proxy2.createAnonymousProxyFactory(lookup, type, new LambdaProxyHandler(target, capturedTypes));
  if (type.parameterCount() == 0) { // no capture
    return new ConstantCallSite(MethodHandles.constant(type.returnType(), mh.invoke()));
  }
  return new ConstantCallSite(mh);
}
 
Example 8
public static void main(String[] args) throws Throwable {
    MethodHandle mh = MethodHandles.lookup().findVirtual(CharSequence.class, "toString", MethodType.methodType(String.class));
    MethodType mt = MethodType.methodType(Object.class, CharSequence.class);
    mh = mh.asType(mt);

    Object res = mh.invokeExact((CharSequence)"123");

    System.out.println("TEST PASSED");
}
 
Example 9
public static void main(String[] args) throws Throwable {
    MethodHandle mh = MethodHandles.lookup().findVirtual(CharSequence.class, "toString", MethodType.methodType(String.class));
    MethodType mt = MethodType.methodType(Object.class, CharSequence.class);
    mh = mh.asType(mt);

    Object res = mh.invokeExact((CharSequence)"123");

    System.out.println("TEST PASSED");
}
 
Example 10
@Test
public void testShortZeroConversion() throws Throwable {
    MethodHandle h1 = MethodHandles.constant(Short.class, (short)42);
    MethodHandle h2 = h1.asType(MethodType.methodType(void.class));  // drop 42
    MethodHandle h3 = h2.asType(MethodType.methodType(short.class));  // add 0
    MethodHandle h4 = h3.asType(MethodType.methodType(Object.class));  // box

    Object x = h4.invokeExact();
    assertEquals(x, (short)0);
    assertTrue(x == Short.valueOf((short)0));
    assertTrue(x == Wrapper.SHORT.zero());
}
 
Example 11
private static MethodHandle unbox(Wrapper wrap, int kind) {
    // kind 0 -> strongly typed with NPE
    // kind 1 -> strongly typed but zero for null,
    // kind 2 -> asType rules: accept multiple box types but only widening conversions with NPE
    // kind 3 -> explicitCastArguments rules: allow narrowing conversions, zero for null
    WrapperCache cache = UNBOX_CONVERSIONS[kind];
    MethodHandle mh = cache.get(wrap);
    if (mh != null) {
        return mh;
    }
    // slow path
    switch (wrap) {
        case OBJECT:
        case VOID:
            throw new IllegalArgumentException("unbox "+wrap);
    }
    // look up the method
    String name = "unbox" + wrap.wrapperSimpleName();
    MethodType type = unboxType(wrap, kind);
    try {
        mh = IMPL_LOOKUP.findStatic(THIS_CLASS, name, type);
    } catch (ReflectiveOperationException ex) {
        mh = null;
    }
    if (mh != null) {
        if (kind > 0) {
            boolean cast = (kind != 2);
            mh = MethodHandles.insertArguments(mh, 1, cast);
        }
        if (kind == 1) {  // casting but exact (null -> zero)
            mh = mh.asType(unboxType(wrap, 0));
        }
        return cache.put(wrap, mh);
    }
    throw new IllegalArgumentException("cannot find unbox adapter for " + wrap
            + (kind <= 1 ? " (exact)" : kind == 3 ? " (cast)" : ""));
}
 
Example 12
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 13
private TestCase(Class<T> rtype, Function<Object, T> cast,
        ThrowMode throwMode, Throwable thrown)
        throws NoSuchMethodException, IllegalAccessException {
    this.cast = cast;
    filter = MethodHandles.lookup().findVirtual(
            Function.class,
            "apply",
            MethodType.methodType(Object.class, Object.class))
                          .bindTo(cast);
    this.rtype = rtype;
    this.throwMode = throwMode;
    this.throwableClass = thrown.getClass();
    switch (throwMode) {
        case NOTHING:
            this.thrown = null;
            break;
        case ADAPTER:
        case UNCAUGHT:
            this.thrown = new Error("do not catch this");
            break;
        default:
            this.thrown = thrown;
    }

    MethodHandle throwOrReturn = THROW_OR_RETURN;
    if (throwMode == ThrowMode.ADAPTER) {
        MethodHandle fakeIdentity = FAKE_IDENTITY.bindTo(this);
        for (int i = 0; i < 10; ++i) {
            throwOrReturn = MethodHandles.filterReturnValue(
                    throwOrReturn, fakeIdentity);
        }
    }
    thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
}
 
Example 14
private static MethodHandle unbox(Wrapper wrap, int kind) {
    // kind 0 -> strongly typed with NPE
    // kind 1 -> strongly typed but zero for null,
    // kind 2 -> asType rules: accept multiple box types but only widening conversions with NPE
    // kind 3 -> explicitCastArguments rules: allow narrowing conversions, zero for null
    WrapperCache cache = UNBOX_CONVERSIONS[kind];
    MethodHandle mh = cache.get(wrap);
    if (mh != null) {
        return mh;
    }
    // slow path
    switch (wrap) {
        case OBJECT:
        case VOID:
            throw new IllegalArgumentException("unbox "+wrap);
    }
    // look up the method
    String name = "unbox" + wrap.wrapperSimpleName();
    MethodType type = unboxType(wrap, kind);
    try {
        mh = IMPL_LOOKUP.findStatic(THIS_CLASS, name, type);
    } catch (ReflectiveOperationException ex) {
        mh = null;
    }
    if (mh != null) {
        if (kind > 0) {
            boolean cast = (kind != 2);
            mh = MethodHandles.insertArguments(mh, 1, cast);
        }
        if (kind == 1) {  // casting but exact (null -> zero)
            mh = mh.asType(unboxType(wrap, 0));
        }
        return cache.put(wrap, mh);
    }
    throw new IllegalArgumentException("cannot find unbox adapter for " + wrap
            + (kind <= 1 ? " (exact)" : kind == 3 ? " (cast)" : ""));
}
 
Example 15
private static MethodHandle unbox(Wrapper wrap, int kind) {
    // kind 0 -> strongly typed with NPE
    // kind 1 -> strongly typed but zero for null,
    // kind 2 -> asType rules: accept multiple box types but only widening conversions with NPE
    // kind 3 -> explicitCastArguments rules: allow narrowing conversions, zero for null
    WrapperCache cache = UNBOX_CONVERSIONS[kind];
    MethodHandle mh = cache.get(wrap);
    if (mh != null) {
        return mh;
    }
    // slow path
    switch (wrap) {
        case OBJECT:
        case VOID:
            throw new IllegalArgumentException("unbox "+wrap);
    }
    // look up the method
    String name = "unbox" + wrap.wrapperSimpleName();
    MethodType type = unboxType(wrap, kind);
    try {
        mh = IMPL_LOOKUP.findStatic(THIS_CLASS, name, type);
    } catch (ReflectiveOperationException ex) {
        mh = null;
    }
    if (mh != null) {
        if (kind > 0) {
            boolean cast = (kind != 2);
            mh = MethodHandles.insertArguments(mh, 1, cast);
        }
        if (kind == 1) {  // casting but exact (null -> zero)
            mh = mh.asType(unboxType(wrap, 0));
        }
        return cache.put(wrap, mh);
    }
    throw new IllegalArgumentException("cannot find unbox adapter for " + wrap
            + (kind <= 1 ? " (exact)" : kind == 3 ? " (cast)" : ""));
}
 
Example 16
@Override
public MethodHandle asType(final MethodHandle handle, final MethodType type) {
    final MethodHandle mh = handle.asType(type);
    return debug(mh, "asType", handle, type);
}
 
Example 17
Source Project: gravel   File: FieldAccessCallSite.java    License: Apache License 2.0 4 votes vote down vote up
protected MethodHandle findFieldAccess(Class receiverClass) {
	MethodHandle access = findAccessOrNil(receiverClass);
	if (access == null)
		throw new RuntimeException("Access not found");
	return access.asType(type);
}
 
Example 18
@Override
public MethodHandle asType(final MethodHandle handle, final MethodType type) {
    final MethodHandle mh = handle.asType(type);
    return debug(mh, "asType", handle, type);
}
 
Example 19
/**
 * Takes a method handle, and returns a potentially different method handle that can be used in
 * {@code ScriptFunction#invoke(Object, Object...)} or {code ScriptFunction#construct(Object, Object...)}.
 * The returned method handle will be sure to return {@code Object}, and will have all its parameters turned into
 * {@code Object} as well, except for the following ones:
 * <ul>
 *   <li>a last parameter of type {@code Object[]} which is used for vararg functions,</li>
 *   <li>the first argument, which is forced to be {@link ScriptFunction}, in case the function receives itself
 *   (callee) as an argument.</li>
 * </ul>
 *
 * @param mh the original method handle
 *
 * @return the new handle, conforming to the rules above.
 */
private static MethodHandle makeGenericMethod(final MethodHandle mh) {
    final MethodType type = mh.type();
    final MethodType newType = makeGenericType(type);
    return type.equals(newType) ? mh : mh.asType(newType);
}
 
Example 20
/**
 * Takes a method handle intended to be used as a guard, and adapts it to
 * the requested type, but returning a boolean. Applies
 * {@link MethodHandle#asType(MethodType)} to convert types and uses
 * {@link MethodHandles#dropArguments(MethodHandle, int, Class...)} to match
 * the requested type arity.
 * @param test the test method handle
 * @param type the type to adapt the method handle to
 * @return the adapted method handle
 */
public static MethodHandle asType(final MethodHandle test, final MethodType type) {
    return test.asType(getTestType(test, type));
}