java.lang.invoke.MethodHandle.type()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(14.4k)|赞(0)|评价(0)|浏览(155)

本文整理了Java中java.lang.invoke.MethodHandle.type()方法的一些代码示例,展示了MethodHandle.type()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MethodHandle.type()方法的具体详情如下:
包路径:java.lang.invoke.MethodHandle
类名称:MethodHandle
方法名:type

MethodHandle.type介绍

[英]Reports the type of this method handle. Every invocation of this method handle via invokeExact must exactly match this type.
[中]报告此方法句柄的类型。通过invokeExact对此方法句柄的每次调用都必须与此类型完全匹配。

代码示例

代码示例来源:origin: prestodb/presto

  1. public Binding bind(MethodHandle method)
  2. {
  3. long bindingId = nextId++;
  4. Binding binding = new Binding(bindingId, method.type());
  5. bindings.put(bindingId, method);
  6. return binding;
  7. }

代码示例来源:origin: prestodb/presto

  1. private static void verifyMethodParameterType(MethodHandle method, int index, Class javaType, String sqlTypeDisplayName)
  2. {
  3. checkArgument(method.type().parameterArray()[index] == javaType,
  4. "Expected method %s parameter %s type to be %s (%s)",
  5. method,
  6. index,
  7. javaType.getName(),
  8. sqlTypeDisplayName);
  9. }

代码示例来源:origin: prestodb/presto

  1. private static void verifyExactOutputFunction(MethodHandle method, List<AccumulatorStateDescriptor> stateDescriptors)
  2. {
  3. if (method == null) {
  4. return;
  5. }
  6. Class<?>[] parameterTypes = method.type().parameterArray();
  7. checkArgument(parameterTypes.length == stateDescriptors.size() + 1, "Number of arguments for combine function must be exactly one plus than number of states.");
  8. for (int i = 0; i < stateDescriptors.size(); i++) {
  9. checkArgument(parameterTypes[i].equals(stateDescriptors.get(i).getStateInterface()), String.format("Type for Parameter index %d is unexpected", i));
  10. }
  11. checkArgument(Arrays.stream(parameterTypes).filter(type -> type.equals(BlockBuilder.class)).count() == 1, "Output function must take exactly one BlockBuilder parameter");
  12. }

代码示例来源:origin: prestodb/presto

  1. /**
  2. * @param f (U, S1, S2, ..., Sm)R
  3. * @param g (T1, T2, ..., Tn)U
  4. * @return (T1, T2, ..., Tn, S1, S2, ..., Sm)R
  5. */
  6. public static MethodHandle compose(MethodHandle f, MethodHandle g)
  7. {
  8. if (f.type().parameterType(0) != g.type().returnType()) {
  9. throw new IllegalArgumentException(format("f.parameter(0) != g.return(). f: %s g: %s", f.type(), g.type()));
  10. }
  11. // Semantics: f => f
  12. // Type: (U, S1, S2, ..., Sn)R => (U, T1, T2, ..., Tm, S1, S2, ..., Sn)R
  13. MethodHandle fUTS = MethodHandles.dropArguments(f, 1, g.type().parameterList());
  14. // Semantics: f => fg
  15. // Type: (U, T1, T2, ..., Tm, S1, S2, ..., Sn)R => (T1, T2, ..., Tm, S1, S2, ..., Sn)R
  16. return MethodHandles.foldArguments(fUTS, g);
  17. }

代码示例来源:origin: prestodb/presto

  1. /**
  2. * @param f (U, S1, S2, ..., Sm)R
  3. * @param g (T1, T2, ..., Tn)U
  4. * @return (T1, T2, ..., Tn, S1, S2, ..., Sm)R
  5. */
  6. public static MethodHandle compose(MethodHandle f, MethodHandle g)
  7. {
  8. if (f.type().parameterType(0) != g.type().returnType()) {
  9. throw new IllegalArgumentException(format("f.parameter(0) != g.return(). f: %s g: %s", f.type(), g.type()));
  10. }
  11. // Semantics: f => f
  12. // Type: (U, S1, S2, ..., Sn)R => (U, T1, T2, ..., Tm, S1, S2, ..., Sn)R
  13. MethodHandle fUTS = MethodHandles.dropArguments(f, 1, g.type().parameterList());
  14. // Semantics: f => fg
  15. // Type: (U, T1, T2, ..., Tm, S1, S2, ..., Sn)R => (T1, T2, ..., Tm, S1, S2, ..., Sn)R
  16. return MethodHandles.foldArguments(fUTS, g);
  17. }

代码示例来源:origin: prestodb/presto

  1. private static void verifyCombineFunction(MethodHandle method, List<Class> lambdaInterfaces, List<AccumulatorStateDescriptor> stateDescriptors)
  2. {
  3. Class<?>[] parameterTypes = method.type().parameterArray();
  4. checkArgument(
  5. parameterTypes.length == stateDescriptors.size() * 2 + lambdaInterfaces.size(),
  6. "Number of arguments for combine function must be 2 times the size of states plus number of lambda channels.");
  7. for (int i = 0; i < stateDescriptors.size() * 2; i++) {
  8. checkArgument(
  9. parameterTypes[i].equals(stateDescriptors.get(i % stateDescriptors.size()).getStateInterface()),
  10. String.format("Type for Parameter index %d is unexpected. Arguments for combine function must appear in the order of state1, state2, ..., otherState1, otherState2, ...", i));
  11. }
  12. for (int i = 0; i < lambdaInterfaces.size(); i++) {
  13. verifyMethodParameterType(method, i + stateDescriptors.size() * 2, lambdaInterfaces.get(i), "function");
  14. }
  15. }

代码示例来源:origin: prestodb/presto

  1. private MethodHandle getMethodHandle(Method method)
  2. {
  3. MethodHandle methodHandle = methodHandle(FUNCTION_IMPLEMENTATION_ERROR, method);
  4. if (!isStatic(method.getModifiers())) {
  5. // Change type of "this" argument to Object to make sure callers won't have classloader issues
  6. methodHandle = methodHandle.asType(methodHandle.type().changeParameterType(0, Object.class));
  7. // Re-arrange the parameters, so that the "this" parameter is after the meta parameters
  8. int[] permutedIndices = new int[methodHandle.type().parameterCount()];
  9. permutedIndices[0] = dependencies.size();
  10. MethodType newType = methodHandle.type().changeParameterType(dependencies.size(), methodHandle.type().parameterType(0));
  11. for (int i = 0; i < dependencies.size(); i++) {
  12. permutedIndices[i + 1] = i;
  13. newType = newType.changeParameterType(i, methodHandle.type().parameterType(i + 1));
  14. }
  15. for (int i = dependencies.size() + 1; i < permutedIndices.length; i++) {
  16. permutedIndices[i] = i;
  17. }
  18. methodHandle = permuteArguments(methodHandle, newType, permutedIndices);
  19. }
  20. return methodHandle;
  21. }

代码示例来源:origin: prestodb/presto

  1. public FieldDefinition getCachedInstance(MethodHandle methodHandle)
  2. {
  3. FieldDefinition field = classDefinition.declareField(a(PRIVATE, FINAL), "__cachedInstance" + nextId, methodHandle.type().returnType());
  4. initializers.put(field, methodHandle);
  5. nextId++;
  6. return field;
  7. }

代码示例来源:origin: robolectric/robolectric

  1. private static MethodHandle cleanStackTraces(MethodHandle mh) {
  2. MethodType type = EXCEPTION_HANDLER.type().changeReturnType(mh.type().returnType());
  3. return catchException(mh, Throwable.class, EXCEPTION_HANDLER.asType(type));
  4. }
  5. }

代码示例来源:origin: prestodb/presto

  1. public Procedure(String schema, String name, List<Argument> arguments, MethodHandle methodHandle)
  2. {
  3. this.schema = checkNotNullOrEmpty(schema, "schema").toLowerCase(ENGLISH);
  4. this.name = checkNotNullOrEmpty(name, "name").toLowerCase(ENGLISH);
  5. this.arguments = unmodifiableList(new ArrayList<>(arguments));
  6. this.methodHandle = requireNonNull(methodHandle, "methodHandle is null");
  7. Set<String> names = new HashSet<>();
  8. for (Argument argument : arguments) {
  9. checkArgument(names.add(argument.getName()), "Duplicate argument name: " + argument.getName());
  10. }
  11. checkArgument(!methodHandle.isVarargsCollector(), "Method must have fixed arity");
  12. checkArgument(methodHandle.type().returnType() == void.class, "Method must return void");
  13. long parameterCount = methodHandle.type().parameterList().stream()
  14. .filter(type -> !ConnectorSession.class.isAssignableFrom(type))
  15. .count();
  16. checkArgument(parameterCount == arguments.size(), "Method parameter count must match arguments");
  17. }

代码示例来源:origin: prestodb/presto

  1. public Procedure(String schema, String name, List<Argument> arguments, MethodHandle methodHandle)
  2. {
  3. this.schema = checkNotNullOrEmpty(schema, "schema").toLowerCase(ENGLISH);
  4. this.name = checkNotNullOrEmpty(name, "name").toLowerCase(ENGLISH);
  5. this.arguments = unmodifiableList(new ArrayList<>(arguments));
  6. this.methodHandle = requireNonNull(methodHandle, "methodHandle is null");
  7. Set<String> names = new HashSet<>();
  8. for (Argument argument : arguments) {
  9. checkArgument(names.add(argument.getName()), "Duplicate argument name: " + argument.getName());
  10. }
  11. checkArgument(!methodHandle.isVarargsCollector(), "Method must have fixed arity");
  12. checkArgument(methodHandle.type().returnType() == void.class, "Method must return void");
  13. long parameterCount = methodHandle.type().parameterList().stream()
  14. .filter(type -> !ConnectorSession.class.isAssignableFrom(type))
  15. .count();
  16. checkArgument(parameterCount == arguments.size(), "Method parameter count must match arguments");
  17. }

代码示例来源:origin: prestodb/presto

  1. private void validateProcedure(Procedure procedure)
  2. {
  3. List<Class<?>> parameters = procedure.getMethodHandle().type().parameterList().stream()
  4. .filter(type -> !ConnectorSession.class.isAssignableFrom(type))
  5. .collect(toList());
  6. for (int i = 0; i < procedure.getArguments().size(); i++) {
  7. Argument argument = procedure.getArguments().get(i);
  8. Type type = typeManager.getType(argument.getType());
  9. Class<?> argumentType = Primitives.unwrap(parameters.get(i));
  10. Class<?> expectedType = getObjectType(type);
  11. checkArgument(expectedType.equals(argumentType),
  12. "Argument '%s' has invalid type %s (expected %s)",
  13. argument.getName(),
  14. argumentType.getName(),
  15. expectedType.getName());
  16. }
  17. }

代码示例来源:origin: prestodb/presto

  1. private InvokeFunctionBytecodeExpression(
  2. Scope scope,
  3. CallSiteBinder binder,
  4. String name,
  5. ScalarFunctionImplementation function,
  6. Optional<BytecodeNode> instance,
  7. List<BytecodeExpression> parameters)
  8. {
  9. super(type(Primitives.unwrap(function.getMethodHandle().type().returnType())));
  10. this.invocation = generateInvocation(
  11. scope,
  12. name,
  13. function,
  14. instance,
  15. parameters.stream().map(BytecodeNode.class::cast).collect(toImmutableList()),
  16. binder);
  17. this.oneLineDescription = name + "(" + Joiner.on(", ").join(parameters) + ")";
  18. }

代码示例来源:origin: apache/kafka

  1. private static MethodHandle unmapJava7Or8(MethodHandles.Lookup lookup) throws ReflectiveOperationException {
  2. /* "Compile" a MethodHandle that is roughly equivalent to the following lambda:
  3. *
  4. * (ByteBuffer buffer) -> {
  5. * sun.misc.Cleaner cleaner = ((java.nio.DirectByteBuffer) byteBuffer).cleaner();
  6. * if (nonNull(cleaner))
  7. * cleaner.clean();
  8. * else
  9. * noop(cleaner); // the noop is needed because MethodHandles#guardWithTest always needs both if and else
  10. * }
  11. */
  12. Class<?> directBufferClass = Class.forName("java.nio.DirectByteBuffer");
  13. Method m = directBufferClass.getMethod("cleaner");
  14. m.setAccessible(true);
  15. MethodHandle directBufferCleanerMethod = lookup.unreflect(m);
  16. Class<?> cleanerClass = directBufferCleanerMethod.type().returnType();
  17. MethodHandle cleanMethod = lookup.findVirtual(cleanerClass, "clean", methodType(void.class));
  18. MethodHandle nonNullTest = lookup.findStatic(MappedByteBuffers.class, "nonNull",
  19. methodType(boolean.class, Object.class)).asType(methodType(boolean.class, cleanerClass));
  20. MethodHandle noop = dropArguments(constant(Void.class, null).asType(methodType(void.class)), 0, cleanerClass);
  21. MethodHandle unmapper = filterReturnValue(directBufferCleanerMethod, guardWithTest(nonNullTest, cleanMethod, noop))
  22. .asType(methodType(void.class, ByteBuffer.class));
  23. return unmapper;
  24. }

代码示例来源:origin: prestodb/presto

  1. @Override
  2. public ScalarFunctionImplementation specialize(
  3. BoundVariables boundVariables, int arity, TypeManager typeManager,
  4. FunctionRegistry functionRegistry)
  5. {
  6. Type toType = boundVariables.getTypeVariable("E");
  7. MethodHandle methodHandle = METHOD_HANDLE_NON_NULL.asType(METHOD_HANDLE_NON_NULL.type().changeReturnType(toType.getJavaType()));
  8. return new ScalarFunctionImplementation(
  9. false,
  10. ImmutableList.of(valueTypeArgumentProperty(RETURN_NULL_ON_NULL)),
  11. methodHandle,
  12. isDeterministic());
  13. }

代码示例来源:origin: prestodb/presto

  1. @Override
  2. public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
  3. {
  4. Type returnType = boundVariables.getTypeVariable("T");
  5. return new ScalarFunctionImplementation(
  6. true,
  7. ImmutableList.of(functionTypeArgumentProperty(InvokeLambda.class)),
  8. METHOD_HANDLE.asType(
  9. METHOD_HANDLE.type()
  10. .changeReturnType(wrap(returnType.getJavaType()))),
  11. isDeterministic());
  12. }

代码示例来源:origin: prestodb/presto

  1. @Test
  2. public void testCustomStateSerializerAggregationParse()
  3. {
  4. ParametricAggregation aggregation = parseFunctionDefinition(CustomStateSerializerAggregationFunction.class);
  5. AggregationImplementation implementation = getOnlyElement(aggregation.getImplementations().getExactImplementations().values());
  6. assertTrue(implementation.getStateSerializerFactory().isPresent());
  7. InternalAggregationFunction specialized = aggregation.specialize(BoundVariables.builder().build(), 1, new TypeRegistry(), null);
  8. AccumulatorStateSerializer<?> createdSerializer = getOnlyElement(((LazyAccumulatorFactoryBinder) specialized.getAccumulatorFactoryBinder())
  9. .getGenericAccumulatorFactoryBinder().getStateDescriptors()).getSerializer();
  10. Class<?> serializerFactory = implementation.getStateSerializerFactory().get().type().returnType();
  11. assertTrue(serializerFactory.isInstance(createdSerializer));
  12. }

代码示例来源:origin: prestodb/presto

  1. @Override
  2. public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
  3. {
  4. Type fromType = boundVariables.getTypeVariable("F");
  5. Type toType = boundVariables.getTypeVariable("T");
  6. Class<?> returnType = Primitives.wrap(toType.getJavaType());
  7. List<ArgumentProperty> argumentProperties;
  8. MethodHandle tryCastHandle;
  9. // the resulting method needs to return a boxed type
  10. Signature signature = functionRegistry.getCoercion(fromType, toType);
  11. ScalarFunctionImplementation implementation = functionRegistry.getScalarFunctionImplementation(signature);
  12. argumentProperties = ImmutableList.of(implementation.getArgumentProperty(0));
  13. MethodHandle coercion = implementation.getMethodHandle();
  14. coercion = coercion.asType(methodType(returnType, coercion.type()));
  15. MethodHandle exceptionHandler = dropArguments(constant(returnType, null), 0, RuntimeException.class);
  16. tryCastHandle = catchException(coercion, RuntimeException.class, exceptionHandler);
  17. return new ScalarFunctionImplementation(true, argumentProperties, tryCastHandle, isDeterministic());
  18. }
  19. }

代码示例来源:origin: prestodb/presto

  1. @Override
  2. public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
  3. {
  4. Type argumentType = boundVariables.getTypeVariable("T");
  5. Type returnType = boundVariables.getTypeVariable("U");
  6. return new ScalarFunctionImplementation(
  7. true,
  8. ImmutableList.of(
  9. valueTypeArgumentProperty(USE_BOXED_TYPE),
  10. functionTypeArgumentProperty(UnaryFunctionInterface.class)),
  11. METHOD_HANDLE.asType(
  12. METHOD_HANDLE.type()
  13. .changeReturnType(wrap(returnType.getJavaType()))
  14. .changeParameterType(0, wrap(argumentType.getJavaType()))),
  15. isDeterministic());
  16. }

代码示例来源:origin: prestodb/presto

  1. @Override
  2. public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
  3. {
  4. Type inputType = boundVariables.getTypeVariable("T");
  5. Type intermediateType = boundVariables.getTypeVariable("S");
  6. Type outputType = boundVariables.getTypeVariable("R");
  7. MethodHandle methodHandle = METHOD_HANDLE.bindTo(inputType);
  8. return new ScalarFunctionImplementation(
  9. true,
  10. ImmutableList.of(
  11. valueTypeArgumentProperty(RETURN_NULL_ON_NULL),
  12. valueTypeArgumentProperty(USE_BOXED_TYPE),
  13. functionTypeArgumentProperty(BinaryFunctionInterface.class),
  14. functionTypeArgumentProperty(UnaryFunctionInterface.class)),
  15. methodHandle.asType(
  16. methodHandle.type()
  17. .changeParameterType(1, Primitives.wrap(intermediateType.getJavaType()))
  18. .changeReturnType(Primitives.wrap(outputType.getJavaType()))),
  19. isDeterministic());
  20. }

相关文章