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


Java MethodHandle类代码示例

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


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

示例1: getTestMH

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
private MethodHandle getTestMH(Class clazz, String methodName,
        Object param, boolean isNegativeTest)
        throws Exception {
    MethodType mType = (param != null)
            ? MethodType.genericMethodType(1)
            : MethodType.methodType(String.class);
    MethodHandles.Lookup lookup = MethodHandles.lookup();
    if (!isNegativeTest) {
        return methodName.equals("staticMethod")
                ? lookup.findStatic(clazz, methodName, mType)
                : lookup.findVirtual(clazz, methodName, mType);
    } else {
        return methodName.equals("staticMethod")
                ? lookup.findVirtual(clazz, methodName, mType)
                : lookup.findStatic(clazz, methodName, mType);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:DefaultStaticInvokeTest.java

示例2: generateMethodTest6

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
/**
 *  Generate test with an invokedynamic, a static bootstrap method with an extra arg that is a
 *  MethodHandle of kind invoke interface. The target method is a default method into an interface
 *  that is at the end of a chain of interfaces.
 */
private void generateMethodTest6(ClassVisitor cv) {
  MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "test6", "()V",
      null, null);
  MethodType mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class,
      MethodType.class, MethodHandle.class);
  Handle bootstrap = new Handle(Opcodes.H_INVOKESTATIC, Type.getInternalName(InvokeCustom.class),
      "bsmCreateCallCallingtargetMethodTest7", mt.toMethodDescriptorString(), false);
  mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(InvokeCustom.class));
  mv.visitInsn(Opcodes.DUP);
  mv.visitMethodInsn(
      Opcodes.INVOKESPECIAL, Type.getInternalName(InvokeCustom.class), "<init>", "()V", false);
  mv.visitInvokeDynamicInsn("targetMethodTest7", "(Linvokecustom/J;)V", bootstrap,
      new Handle(Opcodes.H_INVOKEINTERFACE, Type.getInternalName(J.class),
          "targetMethodTest7", "()V", true));
  mv.visitInsn(Opcodes.RETURN);
  mv.visitMaxs(-1, -1);
}
 
开发者ID:inferjay,项目名称:r8,代码行数:23,代码来源:TestGenerator.java

示例3: generateMethodTest7

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
/**
 *  Generate test with an invokedynamic, a static bootstrap method with an extra arg that is a
 *  MethodHandle of kind invoke interface. The target method is a method into an interface
 *  that is shadowed by another definition into a sub interfaces.
 */
private void generateMethodTest7(ClassVisitor cv) {
  MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "test7", "()V",
      null, null);
  MethodType mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class,
      MethodType.class, MethodHandle.class);
  Handle bootstrap = new Handle(Opcodes.H_INVOKESTATIC, Type.getInternalName(InvokeCustom.class),
      "bsmCreateCallCallingtargetMethodTest8", mt.toMethodDescriptorString(), false);
  mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(InvokeCustom.class));
  mv.visitInsn(Opcodes.DUP);
  mv.visitMethodInsn(
      Opcodes.INVOKESPECIAL, Type.getInternalName(InvokeCustom.class), "<init>", "()V", false);
  mv.visitInvokeDynamicInsn("targetMethodTest8", "(Linvokecustom/J;)V", bootstrap,
      new Handle(Opcodes.H_INVOKEINTERFACE, Type.getInternalName(J.class),
          "targetMethodTest8", "()V", true));
  mv.visitInsn(Opcodes.RETURN);
  mv.visitMaxs(-1, -1);
}
 
开发者ID:inferjay,项目名称:r8,代码行数:23,代码来源:TestGenerator.java

示例4: filter

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
/**
 * ECMA 15.4.4.20 Array.prototype.filter ( callbackfn [ , thisArg ] )
 *
 * @param self        self reference
 * @param callbackfn  callback function per element
 * @param thisArg     this argument
 * @return filtered array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static NativeArray filter(final Object self, final Object callbackfn, final Object thisArg) {
    return new IteratorAction<NativeArray>(Global.toObject(self), callbackfn, thisArg, new NativeArray()) {
        private long to = 0;
        private final MethodHandle filterInvoker = getFILTER_CALLBACK_INVOKER();

        @Override
        protected boolean forEach(final Object val, final long i) throws Throwable {
            if ((boolean)filterInvoker.invokeExact(callbackfn, thisArg, val, i, self)) {
                result.defineOwnProperty(ArrayIndex.getArrayIndex(to++), val);
            }
            return true;
        }
    }.apply();
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:24,代码来源:NativeArray.java

示例5: testInvokePolymorphicWithAllTypes

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
public void testInvokePolymorphicWithAllTypes() {
  try {
    MethodHandle mth =
        MethodHandles.lookup()
            .findStatic(
                InvokePolymorphic.class,
                "testWithAllTypes",
                MethodType.methodType(
                    void.class, boolean.class, char.class, short.class, int.class, long.class,
                    float.class, double.class, String.class, Object.class));
    mth.invokeExact(false,'h', (short) 56, 72, Integer.MAX_VALUE + 42l,
        0.56f, 100.0d, "hello", (Object) "goodbye");
  } catch (Throwable t) {
    t.printStackTrace();
  }
}
 
开发者ID:inferjay,项目名称:r8,代码行数:17,代码来源:InvokePolymorphic.java

示例6: debug

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
private MethodHandle debug(final MethodHandle mh, final Class<?> forType, final Class<?> type, final String tag) {
    if (!Context.DEBUG || !Global.hasInstance()) {
        return mh;
    }

    final Context context = Context.getContextTrusted();
    assert context != null;

    return context.addLoggingToHandle(
            ObjectClassGenerator.class,
            Level.INFO,
            mh,
            0,
            true,
            new Supplier<String>() {
                @Override
                public String get() {
                    return tag + " '" + getKey() + "' (property="+ Debug.id(this) + ", slot=" + getSlot() + " " + getClass().getSimpleName() + " forType=" + stripName(forType) + ", type=" + stripName(type) + ')';
                }
            });
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:22,代码来源:AccessorProperty.java

示例7: findReadWriteObjectForSerialization

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
private final MethodHandle findReadWriteObjectForSerialization(Class<?> cl,
                                                               String methodName,
                                                               Class<?> streamClass) {
    if (!Serializable.class.isAssignableFrom(cl)) {
        return null;
    }

    try {
        Method meth = cl.getDeclaredMethod(methodName, streamClass);
        int mods = meth.getModifiers();
        if (meth.getReturnType() != Void.TYPE ||
                Modifier.isStatic(mods) ||
                !Modifier.isPrivate(mods)) {
            return null;
        }
        meth.setAccessible(true);
        return MethodHandles.lookup().unreflect(meth);
    } catch (NoSuchMethodException ex) {
        return null;
    } catch (IllegalAccessException ex1) {
        throw new InternalError("Error", ex1);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:24,代码来源:ReflectionFactory.java

示例8: testTargetClassInOpenModule

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
public void testTargetClassInOpenModule() throws Throwable {
    // m1/p1.Type
    Class<?> clazz = Class.forName("p1.Type");
    assertEquals(clazz.getModule().getName(), "m1");

    // ensure that this module reads m1
    Module thisModule = getClass().getModule();
    Module m1 = clazz.getModule();
    thisModule.addReads(clazz.getModule());
    assertTrue(m1.isOpen("p1", thisModule));

    Lookup lookup = MethodHandles.privateLookupIn(clazz, MethodHandles.lookup());
    assertTrue(lookup.lookupClass() == clazz);
    assertTrue(lookup.hasPrivateAccess());

    // get obj field
    MethodHandle mh = lookup.findStaticGetter(clazz, "obj", Object.class);
    Object obj = mh.invokeExact();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:PrivateLookupInTests.java

示例9: testInitialize

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

示例10: testInterfaceCast0

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
public void testInterfaceCast0() throws Throwable {
    if (CAN_SKIP_WORKING)  return;
    startTest("interfaceCast");
    assert( (((Object)"foo") instanceof CharSequence));
    assert(!(((Object)"foo") instanceof Iterable));
    for (MethodHandle mh : new MethodHandle[]{
        MethodHandles.identity(String.class),
        MethodHandles.identity(CharSequence.class),
        MethodHandles.identity(Iterable.class)
    }) {
        if (verbosity > 0)  System.out.println("-- mh = "+mh);
        for (Class<?> ctype : new Class<?>[]{
            Object.class, String.class, CharSequence.class,
            Number.class, Iterable.class
        }) {
            if (verbosity > 0)  System.out.println("---- ctype = "+ctype.getName());
            //                           doret  docast
            testInterfaceCast(mh, ctype, false, false);
            testInterfaceCast(mh, ctype, true,  false);
            testInterfaceCast(mh, ctype, false, true);
            testInterfaceCast(mh, ctype, true,  true);
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:MethodHandlesTest.java

示例11: getCached

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
static MethodHandle getCached(final int slot, final boolean isPrimitive, final boolean isGetter) {
    //Reference<Accessors> ref = ACCESSOR_CACHE.get(slot);
    ensure(slot);
    Accessors acc = ACCESSOR_CACHE[slot];
    if (acc == null) {
        acc = new Accessors(slot);
        ACCESSOR_CACHE[slot] = acc;
    }

    return acc.getOrCreate(isPrimitive, isGetter);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:12,代码来源:SpillProperty.java

示例12: createConverter

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
MethodHandle createConverter(final Class<?> sourceType, final Class<?> targetType) throws Exception {
    final MethodType type = MethodType.methodType(targetType, sourceType);
    final MethodHandle identity = IDENTITY_CONVERSION.asType(type);
    MethodHandle last = identity;

    final LookupSupplier lookupSupplier = new LookupSupplier();
    try {
        for(int i = factories.length; i-- > 0;) {
            final GuardedInvocation next = factories[i].convertToType(sourceType, targetType, lookupSupplier);
            if(next != null) {
                last = next.compose(last);
            }
        }
    } finally {
        lookupSupplier.closed = true;
    }

    if(last == identity) {
        return IDENTITY_CONVERSION;
    }
    if(!lookupSupplier.returnedLookup) {
        return last;
    }
    // At least one of the consulted converter factories obtained the
    // lookup, so we must presume the created converter is sensitive to the
    // lookup class and thus we will not cache it.
    throw new NotCacheableConverter(last);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:29,代码来源:TypeConverterFactory.java

示例13: getCreateProgramFunctionHandle

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
private static MethodHandle getCreateProgramFunctionHandle(final Class<?> script) {
    try {
        return LOOKUP.findStatic(script, CREATE_PROGRAM_FUNCTION.symbolName(), CREATE_PROGRAM_FUNCTION_TYPE);
    } catch (NoSuchMethodException | IllegalAccessException e) {
        throw new AssertionError("Failed to retrieve a handle for the program function for " + script.getName(), e);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:8,代码来源:Context.java

示例14: logX

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
@Override
public void logX(sun.util.logging.PlatformLogger.Bridge logger, Level level, Object... args) {
    try {
        MethodHandle handle = lookup.findVirtual(bridgeLoggerClass,
                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);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:36,代码来源:LoggerFinderBackendTest.java

示例15: methodHandles

import java.lang.invoke.MethodHandle; //导入依赖的package包/类
public Stream<MethodHandle> methodHandles(Class<?> target) {
    return Methods.declaredMethodsInAncestors(target)
                  .map(method -> {
                      try {
                          return lookup.unreflect(method);
                      } catch(IllegalAccessException e) {
                          return null;
                      }
                  }).filter(h -> h != null);
}
 
开发者ID:OvercastNetwork,项目名称:ProjectAres,代码行数:11,代码来源:MethodResolver.java


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