本文整理汇总了Java中java.lang.invoke.MethodType类的典型用法代码示例。如果您正苦于以下问题:Java MethodType类的具体用法?Java MethodType怎么用?Java MethodType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MethodType类属于java.lang.invoke包,在下文中一共展示了MethodType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: systemLoadLibraryTest
import java.lang.invoke.MethodType; //导入依赖的package包/类
@Test(dataProvider = "flags")
public void systemLoadLibraryTest(final boolean publicLookup) {
final CallSite cs1 = createGetMethodCallSite(publicLookup, "loadLibrary");
final CallSite cs2 = createCallSite(publicLookup, CALL, MethodType.methodType(void.class, Object.class, Object.class, String.class));
try {
final Object method = cs1.getTarget().invoke(StaticClass.forClass(System.class));
cs2.getTarget().invoke(method, StaticClass.forClass(System.class), "foo");
throw new RuntimeException("should not reach here in any case!");
} catch (final Throwable th) {
if (publicLookup) {
Assert.assertTrue(th instanceof IllegalAccessError);
} else {
Assert.assertTrue(th instanceof AccessControlException);
}
}
}
示例2: generateMethodTest7
import java.lang.invoke.MethodType; //导入依赖的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);
}
示例3: prelinkTransformerTest
import java.lang.invoke.MethodType; //导入依赖的package包/类
@Test
public void prelinkTransformerTest() throws Throwable {
final DynamicLinkerFactory factory = newDynamicLinkerFactory(true);
final boolean[] reachedPrelinkTransformer = { false };
factory.setPrelinkTransformer((final GuardedInvocation inv, final LinkRequest linkRequest, final LinkerServices linkerServices) -> {
reachedPrelinkTransformer[0] = true;
// just identity transformer!
return inv;
});
final MethodType mt = MethodType.methodType(Object.class, Object.class, String.class);
final DynamicLinker linker = factory.createLinker();
final CallSite cs = linker.link(new SimpleRelinkableCallSite(new CallSiteDescriptor(
MethodHandles.publicLookup(), GET_PROPERTY, mt)));
Assert.assertFalse(reachedPrelinkTransformer[0]);
Assert.assertEquals(cs.getTarget().invoke(new Object(), "class"), Object.class);
Assert.assertTrue(reachedPrelinkTransformer[0]);
}
示例4: testOnePermutation
import java.lang.invoke.MethodType; //导入依赖的package包/类
static void testOnePermutation(MethodHandle mh, int[] perm, Object[] args)
throws Throwable {
MethodType mt = mh.type();
MethodType pmt = methodType(mt.returnType(),
unpermuteArgs(perm, mt.parameterArray(), Class[].class));
if (VERBOSE)
System.out.println(Arrays.toString(perm));
testCases += 1;
if (DRY_RUN)
return;
Object res = permuteArguments(mh, pmt, perm).invokeWithArguments(unpermuteArgs(perm, args));
String str = String.valueOf(res);
if (!Arrays.toString(args).equals(str)) {
System.out.println(Arrays.toString(perm)+" "+str+" *** WRONG ***");
}
}
示例5: testInvokePolymorphicWithAllTypes
import java.lang.invoke.MethodType; //导入依赖的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: isApplicable
import java.lang.invoke.MethodType; //导入依赖的package包/类
@Override
boolean isApplicable(final MethodType callSiteType, final SingleDynamicMethod method) {
final MethodType methodType = method.getMethodType();
final int methodArity = methodType.parameterCount();
if(methodArity != callSiteType.parameterCount()) {
return false;
}
// 0th arg is receiver; it doesn't matter for overload
// resolution.
for(int i = 1; i < methodArity; ++i) {
if(!TypeUtilities.isSubtype(callSiteType.parameterType(i), methodType.parameterType(i))) {
return false;
}
}
return true;
}
示例7: testReturnFromArg
import java.lang.invoke.MethodType; //导入依赖的package包/类
@Test
public void testReturnFromArg() throws Throwable {
MethodHandles.Lookup l = MethodHandles.lookup();
MethodHandle consumeIdentity = dropArguments(
identity(String.class), 1, int.class, int.class);
MethodHandle consumeVoid = l.findStatic(
PermuteArgsReturnVoidTest.class, "consumeVoid",
MethodType.methodType(void.class, String.class, int.class, int.class));
MethodHandle f = MethodHandles.foldArguments(consumeIdentity, consumeVoid);
MethodHandle p = MethodHandles.permuteArguments(f, MethodType.methodType(String.class, String.class, int.class, int.class), 0, 2, 1);
String s = (String) p.invoke("IN", 0, 0);
Assert.assertEquals(s.getClass(), String.class);
Assert.assertEquals(s, "IN");
}
示例8: testCountedLoopVoidInit
import java.lang.invoke.MethodType; //导入依赖的package包/类
@Test
public static void testCountedLoopVoidInit() throws Throwable {
MethodHandle fit5 = MethodHandles.constant(int.class, 5);
for (int i = 0; i < 8; i++) {
MethodHandle zero = MethodHandles.zero(void.class);
MethodHandle init = fit5;
MethodHandle body = Counted.MH_printHello;
boolean useNull = (i & 1) != 0, addInitArg = (i & 2) != 0, addBodyArg = (i & 4) != 0;
if (useNull) zero = null;
if (addInitArg) init = MethodHandles.dropArguments(init, 0, int.class);
if (addBodyArg) body = MethodHandles.dropArguments(body, 1, int.class);
System.out.println("testCountedLoopVoidInit i="+i+" : "+Arrays.asList(init, zero, body));
MethodHandle loop = MethodHandles.countedLoop(init, zero, body);
MethodType expectedType = Counted.MT_countedPrinting;
if (addInitArg || addBodyArg)
expectedType = expectedType.insertParameterTypes(0, int.class);
assertEquals(expectedType, loop.type());
if (addInitArg || addBodyArg)
loop.invoke(99);
else
loop.invoke();
}
}
示例9: randomMethodTypeGenerator
import java.lang.invoke.MethodType; //导入依赖的package包/类
/**
* Routine used to obtain a randomly generated method type.
*
* @param arity Arity of returned method type.
* @return MethodType generated randomly.
*/
public static MethodType randomMethodTypeGenerator(int arity) {
final Class<?>[] CLASSES = {
Object.class,
int.class,
boolean.class,
byte.class,
short.class,
char.class,
long.class,
float.class,
double.class
};
if (arity > MAX_ARITY) {
throw new IllegalArgumentException(
String.format("Arity should not exceed %d!", MAX_ARITY));
}
List<Class<?>> list = randomClasses(CLASSES, arity);
list = getParams(list, false, arity);
int i = RNG.nextInt(CLASSES.length + 1);
Class<?> rtype = i == CLASSES.length ? void.class : CLASSES[i];
return MethodType.methodType(rtype, list);
}
示例10: BoxedIntegersWithReverseComparator
import java.lang.invoke.MethodType; //导入依赖的package包/类
public BoxedIntegersWithReverseComparator() {
try {
MethodHandles.Lookup l = MethodHandles.lookup();
MethodType cmpt = MethodType.methodType(
int.class, Object[].class, Object[].class, Comparator.class);
MethodType cmprt = MethodType.methodType(
int.class, Object[].class, int.class, int.class,
Object[].class, int.class, int.class, Comparator.class);
eqc = l.findStatic(Arrays.class, "equals", cmpt.changeReturnType(boolean.class));
eqcr = l.findStatic(Arrays.class, "equals", cmprt.changeReturnType(boolean.class));
cmpc = l.findStatic(Arrays.class, "compare", cmpt);
cmpcr = l.findStatic(Arrays.class, "compare", cmprt);
mismatchc = l.findStatic(Arrays.class, "mismatch", cmpt);
mismatchcr = l.findStatic(Arrays.class, "mismatch", cmprt);
}
catch (Exception e) {
throw new Error(e);
}
}
示例11: getCompiler
import java.lang.invoke.MethodType; //导入依赖的package包/类
Compiler getCompiler(final FunctionNode functionNode, final MethodType actualCallSiteType,
final ScriptObject runtimeScope, final Map<Integer, Type> invalidatedProgramPoints,
final int[] continuationEntryPoints) {
final TypeMap typeMap = typeMap(actualCallSiteType);
final Type[] paramTypes = typeMap == null ? null : typeMap.getParameterTypes(functionNodeId);
final Object typeInformationFile = OptimisticTypesPersistence.getLocationDescriptor(source, functionNodeId, paramTypes);
final Context context = Context.getContextTrusted();
return new Compiler(
context,
context.getEnv(),
getInstallerForNewCode(),
functionNode.getSource(), // source
context.getErrorManager(),
isStrict() | functionNode.isStrict(), // is strict
true, // is on demand
this, // compiledFunction, i.e. this RecompilableScriptFunctionData
typeMap, // type map
getEffectiveInvalidatedProgramPoints(invalidatedProgramPoints, typeInformationFile), // invalidated program points
typeInformationFile,
continuationEntryPoints, // continuation entry points
runtimeScope); // runtime scope
}
示例12: setTarget
import java.lang.invoke.MethodType; //导入依赖的package包/类
@Override
public void setTarget(final MethodHandle newTarget) {
final MethodType type = type();
final boolean isVoid = type.returnType() == void.class;
final Class<?> newSelfType = newTarget.type().parameterType(0);
MethodHandle selfFilter = MH.bindTo(PROFILEENTRY, this);
if (newSelfType != Object.class) {
// new target uses a more precise 'self' type than Object.class. We need to
// convert the filter type. Note that the profileEntry method returns "self"
// argument "as is" and so the cast introduced will succeed for any type.
final MethodType selfFilterType = MethodType.methodType(newSelfType, newSelfType);
selfFilter = selfFilter.asType(selfFilterType);
}
MethodHandle methodHandle = MH.filterArguments(newTarget, 0, selfFilter);
if (isVoid) {
methodHandle = MH.filterReturnValue(methodHandle, MH.bindTo(PROFILEVOIDEXIT, this));
} else {
final MethodType filter = MH.type(type.returnType(), type.returnType());
methodHandle = MH.filterReturnValue(methodHandle, MH.asType(MH.bindTo(PROFILEEXIT, this), filter));
}
super.setTarget(methodHandle);
}
示例13: getGenericType
import java.lang.invoke.MethodType; //导入依赖的package包/类
@Override
MethodType getGenericType() {
// We need to ask the code for its generic type. We can't just rely on this function data's arity, as it's not
// actually correct for lots of built-ins. E.g. ECMAScript 5.1 section 15.5.3.2 prescribes that
// Script.fromCharCode([char0[, char1[, ...]]]) has a declared arity of 1 even though it's a variable arity
// method.
int max = 0;
for(final CompiledFunction fn: code) {
final MethodType t = fn.type();
if(ScriptFunctionData.isVarArg(t)) {
// 2 for (callee, this, args[])
return MethodType.genericMethodType(2, true);
}
final int paramCount = t.parameterCount() - (ScriptFunctionData.needsCallee(t) ? 1 : 0);
if(paramCount > max) {
max = paramCount;
}
}
// +1 for callee
return MethodType.genericMethodType(max + 1);
}
示例14: createConverter
import java.lang.invoke.MethodType; //导入依赖的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;
boolean cacheable = true;
for(int i = factories.length; i-- > 0;) {
final GuardedTypeConversion next = factories[i].convertToType(sourceType, targetType);
if(next != null) {
cacheable = cacheable && next.isCacheable();
final GuardedInvocation conversionInvocation = next.getConversionInvocation();
conversionInvocation.assertType(type);
last = conversionInvocation.compose(last);
}
}
if(last == identity) {
return IDENTITY_CONVERSION;
}
if(cacheable) {
return last;
}
throw new NotCacheableConverter(last);
}
示例15: spreadGuardArguments
import java.lang.invoke.MethodType; //导入依赖的package包/类
private static MethodHandle spreadGuardArguments(final MethodHandle guard, final MethodType descType) {
final MethodType guardType = guard.type();
final int guardParamCount = guardType.parameterCount();
final int descParamCount = descType.parameterCount();
final int spreadCount = guardParamCount - descParamCount + 1;
if (spreadCount <= 0) {
// Guard doesn't dip into the varargs
return guard;
}
final MethodHandle arrayConvertingGuard;
// If the last parameter type of the guard is an array, then it is already itself a guard for a vararg apply
// invocation. We must filter the last argument with toApplyArgs otherwise deeper levels of nesting will fail
// with ClassCastException of NativeArray to Object[].
if(guardType.parameterType(guardParamCount - 1).isArray()) {
arrayConvertingGuard = MH.filterArguments(guard, guardParamCount - 1, NativeFunction.TO_APPLY_ARGS);
} else {
arrayConvertingGuard = guard;
}
return ScriptObject.adaptHandleToVarArgCallSite(arrayConvertingGuard, descParamCount);
}