本文整理匯總了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);
}
}
示例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);
}
示例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);
}
示例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();
}
示例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();
}
}
示例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) + ')';
}
});
}
示例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);
}
}
示例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();
}
示例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]);
}
示例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);
}
}
}
示例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);
}
示例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);
}
示例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);
}
}
示例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);
}
}
示例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);
}