本文整理匯總了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);
}