當前位置: 首頁>>代碼示例>>Java>>正文


Java MethodHandles類代碼示例

本文整理匯總了Java中java.lang.invoke.MethodHandles的典型用法代碼示例。如果您正苦於以下問題:Java MethodHandles類的具體用法?Java MethodHandles怎麽用?Java MethodHandles使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MethodHandles類屬於java.lang.invoke包,在下文中一共展示了MethodHandles類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
public static void main(String[] args) throws Throwable {
  MethodHandles.Lookup lookup = MethodHandles.lookup();
  // mt is (char,char)String
  MethodType mt = MethodType.methodType(void.class, Object.class);
  MethodHandle mh = lookup.findVirtual(MethodHandleTest.class, "print", mt);
  mh = mh.bindTo(new MethodHandleTest());

  mh.invoke("Hello World");

  /*
   * Consumer cs = new PartTest_test_FuncIfImpl_0(mh);
   *
   * ArrayList list = new ArrayList(); list.add("Hello1"); list.add("Hello2");
   *
   * list.stream().forEach(cs);
   */

}
 
開發者ID:Samsung,項目名稱:MeziLang,代碼行數:19,代碼來源:MethodHandleTest.java

示例2: handleDefault

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
private Object handleDefault(Object proxy, Method method, Object[] args) throws Throwable {
	// support default messages in interfaces
	if (method.isDefault()) {
		final Class<?> declaringClass = method.getDeclaringClass();
		final MethodHandles.Lookup lookup = MethodHandles.publicLookup().in(declaringClass);
		// ensure allowed mode will not check visibility
		final Field f = MethodHandles.Lookup.class.getDeclaredField("allowedModes");
		final int modifiers = f.getModifiers();
		if (Modifier.isFinal(modifiers)) { // should be done a single time
			final Field modifiersField = Field.class.getDeclaredField("modifiers");
			modifiersField.setAccessible(true);
			modifiersField.setInt(f, modifiers & ~Modifier.FINAL);
			f.setAccessible(true);
			f.set(lookup, MethodHandles.Lookup.PRIVATE);
		}
		return lookup.unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
	}
	return null;
}
 
開發者ID:tudrobotics,項目名稱:urdriver,代碼行數:20,代碼來源:URScriptInvocationHandler.java

示例3: setup

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
@BeforeClass
public void setup() throws Exception {
    vhFinalField = MethodHandles.lookup().findVarHandle(
            VarHandleTestMethodTypeShort.class, "final_v", short.class);

    vhField = MethodHandles.lookup().findVarHandle(
            VarHandleTestMethodTypeShort.class, "v", short.class);

    vhStaticFinalField = MethodHandles.lookup().findStaticVarHandle(
        VarHandleTestMethodTypeShort.class, "static_final_v", short.class);

    vhStaticField = MethodHandles.lookup().findStaticVarHandle(
        VarHandleTestMethodTypeShort.class, "static_v", short.class);

    vhArray = MethodHandles.arrayElementVarHandle(short[].class);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:VarHandleTestMethodTypeShort.java

示例4: setupVarHandleSources

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
@Override
public void setupVarHandleSources() {
    // Combinations of VarHandle byte[] or ByteBuffer
    vhss = new ArrayList<>();
    for (MemoryMode endianess : Arrays.asList(MemoryMode.BIG_ENDIAN, MemoryMode.LITTLE_ENDIAN)) {

        ByteOrder bo = endianess == MemoryMode.BIG_ENDIAN
                ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
        VarHandleSource aeh = new VarHandleSource(
                MethodHandles.byteArrayViewVarHandle(int[].class, bo),
                endianess, MemoryMode.READ_WRITE);
        vhss.add(aeh);

        VarHandleSource bbh = new VarHandleSource(
                MethodHandles.byteBufferViewVarHandle(int[].class, bo),
                endianess, MemoryMode.READ_WRITE);
        vhss.add(bbh);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:20,代碼來源:VarHandleTestByteArrayAsInt.java

示例5: bootstrapMethod

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
/**
 * A bootstrap method for invokedynamic
 * @param lookup a lookup object
 * @param methodName methodName
 * @param type method type
 * @return CallSite for method
 */
public static CallSite bootstrapMethod(MethodHandles.Lookup lookup,
        String methodName, MethodType type) throws IllegalAccessException,
        NoSuchMethodException {
    MethodType mtype = MethodType.methodType(boolean.class,
            new Class<?>[]{int.class, long.class, float.class,
                double.class, String.class});
    return new ConstantCallSite(lookup.findVirtual(lookup.lookupClass(),
            methodName, mtype));
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:InvokeDynamic.java

示例6: createMegamorphicHandle

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
/**
 * Creates the {@link MethodHandle} for the megamorphic call site
 * using {@link ClassValue} and {@link MethodHandles#exactInvoker(MethodType)}:
 */
private MethodHandle createMegamorphicHandle() {
    final MethodType type = type();
    final ClassValue<MethodHandle> megamorphicCache = new ClassValue<MethodHandle>() {
        @Override
        protected MethodHandle computeValue(Class<?> receiverType) {
            // it's too stupid that we cannot throw checked exceptions... (use rethrow puzzler):
            try {
                return lookup(flavor, name, receiverType).asType(type);
            } catch (Throwable t) {
                Def.rethrow(t);
                throw new AssertionError();
            }
        }
    };
    return MethodHandles.foldArguments(MethodHandles.exactInvoker(type),
            MEGAMORPHIC_LOOKUP.bindTo(megamorphicCache));            
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:22,代碼來源:DefBootstrap.java

示例7: testTwoTypes

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
public void testTwoTypes() throws Throwable {
    CallSite site = DefBootstrap.bootstrap(MethodHandles.publicLookup(), 
                                              "toString", 
                                              MethodType.methodType(String.class, Object.class), 
                                              0,
                                              DefBootstrap.METHOD_CALL, "");
    MethodHandle handle = site.dynamicInvoker();
    assertDepthEquals(site, 0);

    assertEquals("5", (String)handle.invokeExact((Object)5));
    assertDepthEquals(site, 1);
    assertEquals("1.5", (String)handle.invokeExact((Object)1.5f));
    assertDepthEquals(site, 2);

    // both these should be cached
    assertEquals("6", (String)handle.invokeExact((Object)6));
    assertDepthEquals(site, 2);
    assertEquals("2.5", (String)handle.invokeExact((Object)2.5f));
    assertDepthEquals(site, 2);
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:21,代碼來源:DefBootstrapTests.java

示例8: setup

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
@BeforeClass
public void setup() throws Exception {
    vhFinalField = MethodHandles.lookup().findVarHandle(
            VarHandleTestMethodHandleAccessFloat.class, "final_v", float.class);

    vhField = MethodHandles.lookup().findVarHandle(
            VarHandleTestMethodHandleAccessFloat.class, "v", float.class);

    vhStaticFinalField = MethodHandles.lookup().findStaticVarHandle(
        VarHandleTestMethodHandleAccessFloat.class, "static_final_v", float.class);

    vhStaticField = MethodHandles.lookup().findStaticVarHandle(
        VarHandleTestMethodHandleAccessFloat.class, "static_v", float.class);

    vhArray = MethodHandles.arrayElementVarHandle(float[].class);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:VarHandleTestMethodHandleAccessFloat.java

示例9: relinkComposableInvoker

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
private static void relinkComposableInvoker(final CallSite cs, final CompiledFunction inv, final boolean constructor) {
    final HandleAndAssumptions handleAndAssumptions = inv.getValidOptimisticInvocation(new Supplier<MethodHandle>() {
        @Override
        public MethodHandle get() {
            return inv.getInvokerOrConstructor(constructor);
        }
    });
    final MethodHandle handle = handleAndAssumptions.handle;
    final SwitchPoint assumptions = handleAndAssumptions.assumptions;
    final MethodHandle target;
    if(assumptions == null) {
        target = handle;
    } else {
        final MethodHandle relink = MethodHandles.insertArguments(RELINK_COMPOSABLE_INVOKER, 0, cs, inv, constructor);
        target = assumptions.guardWithTest(handle, MethodHandles.foldArguments(cs.dynamicInvoker(), relink));
    }
    cs.setTarget(target.asType(cs.type()));
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:CompiledFunction.java

示例10: testFilterArguments

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
void testFilterArguments(int nargs, int pos) throws Throwable {
    countTest();
    MethodHandle target = varargsList(nargs);
    MethodHandle filter = varargsList(1);
    filter = filter.asType(filter.type().generic());
    Object[] argsToPass = randomArgs(nargs, Object.class);
    if (verbosity >= 3)
        System.out.println("filter "+target+" at "+pos+" with "+filter);
    MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
    // Simulate expected effect of filter on arglist:
    Object[] filteredArgs = argsToPass.clone();
    filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
    List<Object> expected = Arrays.asList(filteredArgs);
    Object result = target2.invokeWithArguments(argsToPass);
    if (verbosity >= 3)
        System.out.println("result: "+result);
    if (!expected.equals(result))
        System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
    assertEquals(expected, result);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:MethodHandlesTest.java

示例11: testTargetClassInOpenModule

import java.lang.invoke.MethodHandles; //導入依賴的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

示例12: setup

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
@BeforeClass
public void setup() throws Exception {
    vhFinalField = MethodHandles.lookup().findVarHandle(
            VarHandleTestMethodTypeChar.class, "final_v", char.class);

    vhField = MethodHandles.lookup().findVarHandle(
            VarHandleTestMethodTypeChar.class, "v", char.class);

    vhStaticFinalField = MethodHandles.lookup().findStaticVarHandle(
        VarHandleTestMethodTypeChar.class, "static_final_v", char.class);

    vhStaticField = MethodHandles.lookup().findStaticVarHandle(
        VarHandleTestMethodTypeChar.class, "static_v", char.class);

    vhArray = MethodHandles.arrayElementVarHandle(char[].class);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:VarHandleTestMethodTypeChar.java

示例13: testPublicLookupToUnnamedModule

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
/**
 * Teleport from publicLookup to public type in unnamed module
 *
 * [A0] has PUBLIC access
 */
public void testPublicLookupToUnnamedModule() throws Exception {
    Lookup lookup = MethodHandles.publicLookup().in(unnamedClass);
    assertTrue(lookup.lookupModes() == PUBLIC); // A0

    // m1
    findConstructor(lookup, p1_Type1, void.class);
    findConstructorExpectingIAE(lookup, p2_Type2, void.class);

    // m2
    findConstructor(lookup, q1_Type1, void.class);
    findConstructorExpectingIAE(lookup, q2_Type2, void.class);

    // java.base
    findConstructor(lookup, Object.class, void.class);
    findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);

    // unnamed
    findConstructor(lookup, unnamedClass, void.class);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:25,代碼來源:Main.java

示例14: setup

import java.lang.invoke.MethodHandles; //導入依賴的package包/類
@BeforeClass
public void setup() throws Exception {
    vhFinalField = MethodHandles.lookup().findVarHandle(
            VarHandleTestMethodHandleAccessShort.class, "final_v", short.class);

    vhField = MethodHandles.lookup().findVarHandle(
            VarHandleTestMethodHandleAccessShort.class, "v", short.class);

    vhStaticFinalField = MethodHandles.lookup().findStaticVarHandle(
        VarHandleTestMethodHandleAccessShort.class, "static_final_v", short.class);

    vhStaticField = MethodHandles.lookup().findStaticVarHandle(
        VarHandleTestMethodHandleAccessShort.class, "static_v", short.class);

    vhArray = MethodHandles.arrayElementVarHandle(short[].class);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:VarHandleTestMethodHandleAccessShort.java

示例15: testThrowException

import java.lang.invoke.MethodHandles; //導入依賴的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


注:本文中的java.lang.invoke.MethodHandles類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。