当前位置: 首页>>代码示例>>Java>>正文


Java MethodHandle.asType方法代码示例

本文整理汇总了Java中java.lang.invoke.MethodHandle.asType方法的典型用法代码示例。如果您正苦于以下问题:Java MethodHandle.asType方法的具体用法?Java MethodHandle.asType怎么用?Java MethodHandle.asType使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.lang.invoke.MethodHandle的用法示例。


在下文中一共展示了MethodHandle.asType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testIterateLength

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
@Test(dataProvider = "iteratorInits")
public static void testIterateLength(MethodHandle iterator) throws Throwable {
    MethodHandle body = Iterate.MH_lengthStep;
    MethodHandle init = Iterate.MH_lengthInit;
    MethodType expectedType = Iterate.MT_length;
    int barity = body.type().parameterCount();
    Class<?> iteratorSource = iterator == null ? null : iterator.type().parameterType(0);
    if (iterator != null && iteratorSource != body.type().parameterType(barity-1)) {
        // adjust body to accept the other type
        body = body.asType(body.type().changeParameterType(barity-1, iteratorSource));
        init = init.asType(init.type().changeParameterType(0, iteratorSource));
        expectedType = expectedType.changeParameterType(0, iteratorSource);
    }
    for (;; init = snip(init)) {
        System.out.println("testIterateLength.init = "+init);
        MethodHandle loop = MethodHandles.iteratedLoop(iterator, init, body);
        assertEquals(expectedType, loop.type());
        List<Double> list = Arrays.asList(23.0, 148.0, 42.0);
        assertEquals(list.size(), (int) loop.invoke(list));
        if (init == null)  break;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:LoopCombinatorTest.java

示例2: testThrowException

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
    countTest();
    Class<? extends Throwable> exType = thrown.getClass();
    MethodHandle target = MethodHandles.throwException(returnType, exType);
    //System.out.println("throwing with "+target+" : "+thrown);
    MethodType expectedType = MethodType.methodType(returnType, exType);
    assertEquals(expectedType, target.type());
    target = target.asType(target.type().generic());
    Throwable caught = null;
    try {
        Object res = target.invokeExact((Object) thrown);
        fail("got "+res+" instead of throwing "+thrown);
    } catch (Throwable ex) {
        if (ex != thrown) {
            if (ex instanceof Error)  throw (Error)ex;
            if (ex instanceof RuntimeException)  throw (RuntimeException)ex;
        }
        caught = ex;
    }
    assertSame(thrown, caught);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:MethodHandlesTest.java

示例3: test

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
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);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:17,代码来源:VMAnonymousClass.java

示例4: bsmLookupStaticWithExtraArgs

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
public static CallSite bsmLookupStaticWithExtraArgs(
    MethodHandles.Lookup caller, String name, MethodType type, int i, long l, float f, double d)
    throws NoSuchMethodException, IllegalAccessException {
  System.out.println(i);
  System.out.println(l);
  System.out.println(f);
  System.out.println(d);
  final MethodHandles.Lookup lookup = MethodHandles.lookup();
  final MethodHandle targetMH = lookup.findStatic(lookup.lookupClass(), name, type);
  return new ConstantCallSite(targetMH.asType(type));
}
 
开发者ID:inferjay,项目名称:r8,代码行数:12,代码来源:InvokeCustom.java

示例5: matchReturnTypes

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
static MethodPair matchReturnTypes(final MethodHandle m1, final MethodHandle m2) {
    final MethodType type1 = m1.type();
    final MethodType type2 = m2.type();
    final Class<?> commonRetType = InternalTypeUtilities.getCommonLosslessConversionType(type1.returnType(),
            type2.returnType());
    return new MethodPair(
            m1.asType(type1.changeReturnType(commonRetType)),
            m2.asType(type2.changeReturnType(commonRetType)));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:10,代码来源:AbstractJavaLinker.java

示例6: testIntZeroConversion

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
@Test
public void testIntZeroConversion() throws Throwable {
    MethodHandle h1 = MethodHandles.constant(Integer.class, 42);
    MethodHandle h2 = h1.asType(MethodType.methodType(void.class));  // drop 42
    MethodHandle h3 = h2.asType(MethodType.methodType(int.class));  // add 0
    MethodHandle h4 = h3.asType(MethodType.methodType(Object.class));  // box

    Object x = h4.invokeExact();
    assertEquals(x, 0);
    assertTrue(x == Integer.valueOf(0));
    assertTrue(x == Wrapper.INT.zero());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:WrapperTest.java

示例7: changeArgTypes

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
static MethodHandle changeArgTypes(MethodHandle target,
        int beg, int end, Class<?> argType) {
    MethodType targetType = target.type();
    end = Math.min(end, targetType.parameterCount());
    ArrayList<Class<?>> argTypes = new ArrayList<>(targetType.parameterList());
    Collections.fill(argTypes.subList(beg, end), argType);
    MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
    return target.asType(ttype2);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:10,代码来源:MethodHandlesTest.java

示例8: testConvert

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
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
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:34,代码来源:ValueConversionsTest.java

示例9: testLongZeroConversion

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
@Test
public void testLongZeroConversion() throws Throwable {
    MethodHandle h1 = MethodHandles.constant(Long.class, 42L);
    MethodHandle h2 = h1.asType(MethodType.methodType(void.class));  // drop 42
    MethodHandle h3 = h2.asType(MethodType.methodType(long.class));  // add 0
    MethodHandle h4 = h3.asType(MethodType.methodType(Object.class));  // box

    Object x = h4.invokeExact();
    assertEquals(x, 0L);
    assertTrue(x == Long.valueOf(0));
    assertTrue(x == Wrapper.LONG.zero());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:WrapperTest.java

示例10: testFilterReturnValue

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
    countTest();
    MethodHandle target = varargsList(nargs, rtype);
    MethodHandle filter;
    if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
        filter = varargsList(1);  // add another layer of list-ness
    else
        filter = MethodHandles.identity(rtype);
    filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
    Object[] argsToPass = randomArgs(nargs, Object.class);
    if (verbosity >= 3)
        System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
    MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
    if (verbosity >= 4)
        System.out.println("filtered target: "+target2);
    // Simulate expected effect of filter on return value:
    Object unfiltered = target.invokeWithArguments(argsToPass);
    Object expected = filter.invokeWithArguments(unfiltered);
    if (verbosity >= 4)
        System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
    if (verbosity >= 4)
        System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
    Object result = target2.invokeWithArguments(argsToPass);
    if (verbosity >= 3)
        System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
    if (!expected.equals(result))
        System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
    assertEquals(expected, result);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:30,代码来源:MethodHandlesTest.java

示例11: testShortZeroConversion

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
@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());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:WrapperTest.java

示例12: unbox

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
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)" : ""));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:38,代码来源:ValueConversions.java

示例13: TestCase

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
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));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:35,代码来源:CatchExceptionTest.java

示例14: testByteZeroConversion

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
@Test
public void testByteZeroConversion() throws Throwable {
    MethodHandle h1 = MethodHandles.constant(Byte.class, (byte)42);
    MethodHandle h2 = h1.asType(MethodType.methodType(void.class));  // drop 42
    MethodHandle h3 = h2.asType(MethodType.methodType(byte.class));  // add 0
    MethodHandle h4 = h3.asType(MethodType.methodType(Object.class));  // box

    Object x = h4.invokeExact();
    assertEquals(x, (byte)0);
    assertTrue(x == Byte.valueOf((byte)0));
    assertTrue(x == Wrapper.BYTE.zero());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:WrapperTest.java

示例15: testInterfaceCast

import java.lang.invoke.MethodHandle; //导入方法依赖的package包/类
public void testInterfaceCast(MethodHandle mh, Class<?> ctype,
                                               boolean doret, boolean docast) throws Throwable {
    MethodHandle mh0 = mh;
    if (verbosity > 1)
        System.out.println("mh="+mh+", ctype="+ctype.getName()+", doret="+doret+", docast="+docast);
    String normalRetVal = "normal return value";
    MethodType mt = mh.type();
    MethodType mt0 = mt;
    if (doret)  mt = mt.changeReturnType(ctype);
    else        mt = mt.changeParameterType(0, ctype);
    if (docast) mh = MethodHandles.explicitCastArguments(mh, mt);
    else        mh = mh.asType(mt);
    assertEquals(mt, mh.type());
    MethodType mt1 = mt;
    // this bit is needed to make the interface types disappear for invokeWithArguments:
    mh = MethodHandles.explicitCastArguments(mh, mt.generic());
    Class<?>[] step = {
        mt1.parameterType(0),  // param as passed to mh at first
        mt0.parameterType(0),  // param after incoming cast
        mt0.returnType(),      // return value before cast
        mt1.returnType(),      // return value after outgoing cast
    };
    // where might a checkCast occur?
    boolean[] checkCast = new boolean[step.length];
    // the string value must pass each step without causing an exception
    if (!docast) {
        if (!doret) {
            if (step[0] != step[1])
                checkCast[1] = true;  // incoming value is cast
        } else {
            if (step[2] != step[3])
                checkCast[3] = true;  // outgoing value is cast
        }
    }
    boolean expectFail = false;
    for (int i = 0; i < step.length; i++) {
        Class<?> c = step[i];
        if (!checkCast[i])  c = i2o(c);
        if (!c.isInstance(normalRetVal)) {
            if (verbosity > 3)
                System.out.println("expect failure at step "+i+" in "+Arrays.toString(step)+Arrays.toString(checkCast));
            expectFail = true;
            break;
        }
    }
    countTest(!expectFail);
    if (verbosity > 2)
        System.out.println("expectFail="+expectFail+", mt="+mt);
    Object res;
    try {
        res = mh.invokeWithArguments(normalRetVal);
    } catch (Exception ex) {
        res = ex;
    }
    boolean sawFail = !(res instanceof String);
    if (sawFail != expectFail) {
        System.out.println("*** testInterfaceCast: mh0 = "+mh0);
        System.out.println("  retype using "+(docast ? "explicitCastArguments" : "asType")+" to "+mt+" => "+mh);
        System.out.println("  call returned "+res);
        System.out.println("  expected "+(expectFail ? "an exception" : normalRetVal));
    }
    if (!expectFail) {
        assertFalse(res.toString(), sawFail);
        assertEquals(normalRetVal, res);
    } else {
        assertTrue(res.toString(), sawFail);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:69,代码来源:MethodHandlesTest.java


注:本文中的java.lang.invoke.MethodHandle.asType方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。