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

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

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

MethodHandle.invoke介绍

[英]Invokes the method handle, allowing any caller type descriptor, and optionally performing conversions on arguments and return values.

If the call site's symbolic type descriptor exactly matches this method handle's #type, the call proceeds as if by #invokeExact.

Otherwise, the call proceeds as if this method handle were first adjusted by calling #asType to adjust this method handle to the required type, and then the call proceeds as if by #invokeExact on the adjusted method handle.

There is no guarantee that the asType call is actually made. If the JVM can predict the results of making the call, it may perform adaptations directly on the caller's arguments, and call the target method handle according to its own exact type.

The resolved type descriptor at the call site of invoke must be a valid argument to the receivers asType method. In particular, the caller must specify the same argument arity as the callee's type, if the callee is not a #asVarargsCollector.

When this method is observed via the Core Reflection API, it will appear as a single native method, taking an object array and returning an object. If this native method is invoked directly via java.lang.reflect.Method#invoke, via JNI, or indirectly via java.lang.invoke.MethodHandles.Lookup#unreflect, it will throw an UnsupportedOperationException.
[中]调用方法句柄,允许调用任何调用方类型描述符,并可选地对参数和返回值执行转换。
如果调用站点的符号类型描述符与此方法句柄的#类型完全匹配,则调用将按#invokeExact进行。
否则,调用将继续进行,就好像首先通过调用#asType将此方法句柄调整为所需类型来调整此方法句柄一样,然后调用将继续进行,就好像是通过调整后的方法句柄上的#invokeExact一样。
不能保证asType调用是实际进行的。如果JVM可以预测调用的结果,那么它可以直接对调用方的参数执行调整,并根据自己的确切类型调用目标方法句柄。
invoke调用站点上解析的类型描述符必须是接收方asType方法的有效参数。特别是,如果被调用方不是#asVarargsCollector,则调用方必须指定与被调用方类型相同的参数arity。
当通过Core Reflection API观察此方法时,它将显示为一个单一的本机方法,获取一个对象数组并返回一个对象。如果直接通过java调用此本机方法。朗。反思。方法#通过JNI调用,或通过java间接调用。lang.invoke。方法句柄。Lookup#unreflect,它将抛出一个UnsupportedOperationException。

代码示例

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

@Override
  public Checksum create() {
    try {
      return (Checksum) CONSTRUCTOR.invoke();
    } catch (Throwable throwable) {
      // Should never happen
      throw new RuntimeException(throwable);
    }
  }
}

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

public Runnable embedVersion(Runnable runnable)
  {
    requireNonNull(runnable, "runnable is null");
    try {
      return (Runnable) runnableConstructor.invoke(runnable);
    }
    catch (Throwable throwable) {
      throwIfUnchecked(throwable);
      throw new RuntimeException(throwable);
    }
  }
}

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

private static int offset( String value )
{
  try
  {
    return getOffset == null ? 0 : (int) getOffset.invoke( value );
  }
  catch ( Throwable e )
  {
    throw new AssertionError(
        "This encoder depends being able to access the offset in the char[] array in java.lang.String, " +
        "which failed: " +
        e.getMessage(), e );
  }
}

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

@Override
public OutputStream wrapForOutput(ByteBufferOutputStream buffer, byte messageVersion) {
  try {
    return (OutputStream) ZstdConstructors.OUTPUT.invoke(buffer);
  } catch (Throwable e) {
    throw new KafkaException(e);
  }
}

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

@Override
public OutputStream wrapForOutput(ByteBufferOutputStream buffer, byte messageVersion) {
  try {
    return (OutputStream) SnappyConstructors.OUTPUT.invoke(buffer);
  } catch (Throwable e) {
    throw new KafkaException(e);
  }
}

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

@Override
public Work<Block> project(ConnectorSession session, DriverYieldSignal yieldSignal, Page page, SelectedPositions selectedPositions)
{
  blockBuilder = blockBuilder.newBlockBuilderLike(null);
  try {
    return (Work<Block>) pageProjectionWorkFactory.invoke(blockBuilder, session, page, selectedPositions);
  }
  catch (Throwable e) {
    throw new RuntimeException(e);
  }
}

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

@Override
public void close()
{
  try
  {
    cleanHandle.invoke( cleaner );
  }
  catch ( Throwable throwable )
  {
    throw new LinkageError( "Unable to clean cleaner.", throwable );
  }
}

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

private Object getValue( Object record ) throws ProcedureException
  {
    try
    {
      return getter.invoke( record );
    }
    catch ( Throwable throwable )
    {
      throw new ProcedureException( Status.Procedure.ProcedureCallFailed, throwable,
          "Unable to read value from record `%s`: %s", record, throwable.getMessage() );
    }
  }
}

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

private static Object globalCleaner()
{
  MethodHandles.Lookup lookup = MethodHandles.lookup();
  try
  {
    Class<?> newCleaner = Class.forName( "java.lang.ref.Cleaner" );
    MethodHandle createInstance = lookup.findStatic( newCleaner, "create", MethodType.methodType( newCleaner ) );
    return createInstance.invoke();
  }
  catch ( Throwable throwable )
  {
    return null;
  }
}

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

private static boolean isDeterminateConstant(RowExpression expression, MethodHandle isIndeterminateFunction)
  {
    if (!(expression instanceof ConstantExpression)) {
      return false;
    }
    ConstantExpression constantExpression = (ConstantExpression) expression;
    Object value = constantExpression.getValue();
    boolean isNull = value == null;
    if (isNull) {
      return false;
    }
    try {
      return !(boolean) isIndeterminateFunction.invoke(value, false);
    }
    catch (Throwable t) {
      throwIfUnchecked(t);
      throw new RuntimeException(t);
    }
  }
}

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

@Override
  public InputStream wrapForInput(ByteBuffer buffer, byte messageVersion, BufferSupplier decompressionBufferSupplier) {
    try {
      return (InputStream) SnappyConstructors.INPUT.invoke(new ByteBufferInputStream(buffer));
    } catch (Throwable e) {
      throw new KafkaException(e);
    }
  }
},

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

@Override
  public InputStream wrapForInput(ByteBuffer buffer, byte messageVersion, BufferSupplier decompressionBufferSupplier) {
    try {
      return (InputStream) ZstdConstructors.INPUT.invoke(new ByteBufferInputStream(buffer));
    } catch (Throwable e) {
      throw new KafkaException(e);
    }
  }
};

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

void apply( org.neo4j.kernel.api.proc.Context ctx, Object object ) throws ProcedureException
  {
    try
    {
      setter.invoke( object, provider.apply( ctx ) );
    }
    catch ( Throwable e )
    {
      throw new ProcedureException( Status.Procedure.ProcedureCallFailed, e,
          "Unable to inject component to field `%s`, please ensure it is public and non-final: %s",
          field.getName(), e.getMessage() );
    }
  }
}

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

private static MethodHandle bindInstanceFactory(MethodHandle method, ScalarFunctionImplementation implementation)
{
  if (!implementation.getInstanceFactory().isPresent()) {
    return method;
  }
  try {
    return method.bindTo(implementation.getInstanceFactory().get().invoke());
  }
  catch (Throwable throwable) {
    throw propagate(throwable);
  }
}

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

private static AccumulatorStateSerializer<?> getAccumulatorStateSerializer(AggregationImplementation implementation, BoundVariables variables, TypeManager typeManager, FunctionRegistry functionRegistry, Class<?> stateClass, DynamicClassLoader classLoader)
{
  AccumulatorStateSerializer<?> stateSerializer;
  Optional<MethodHandle> stateSerializerFactory = implementation.getStateSerializerFactory();
  if (stateSerializerFactory.isPresent()) {
    try {
      MethodHandle factoryHandle = bindDependencies(stateSerializerFactory.get(), implementation.getStateSerializerFactoryDependencies(), variables, typeManager, functionRegistry);
      stateSerializer = (AccumulatorStateSerializer<?>) factoryHandle.invoke();
    }
    catch (Throwable t) {
      throwIfUnchecked(t);
      throw new RuntimeException(t);
    }
  }
  else {
    stateSerializer = generateStateSerializer(stateClass, classLoader);
  }
  return stateSerializer;
}

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

@Test
public void shouldGenerateDefaultConstructor() throws Throwable
{
  // given
  ClassHandle handle;
  try ( ClassGenerator simple = generateClass( NamedBase.class, "SimpleClass" ) )
  {
    handle = simple.handle();
  }
  // when
  Object instance = constructor( handle.loadClass() ).invoke();
  Object constructorCalled = instanceMethod( instance, "defaultConstructorCalled" ).invoke();
  // then
  assertTrue( (Boolean) constructorCalled );
}

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

@TypeParameter("T")
@SqlType(StandardTypes.BIGINT)
public static long hash(
    @OperatorDependency(operator = HASH_CODE, returnType = StandardTypes.BIGINT, argumentTypes = {"T"}) MethodHandle hashFunction,
    @TypeParameter("T") Type type,
    @SqlType("array(T)") Block block)
{
  try {
    long hash = 0;
    for (int i = 0; i < block.getPositionCount(); i++) {
      hash = CombineHashFunction.getHash(hash, block.isNull(i) ? NULL_HASH_CODE : (long) hashFunction.invoke(readNativeValue(type, block, i)));
    }
    return hash;
  }
  catch (Throwable t) {
    throw internalError(t);
  }
}

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

@Test
public void testSelectsMethodBasedOnReturnType()
    throws Throwable
{
  SqlScalarFunction function = SqlScalarFunction.builder(TestMethods.class)
      .signature(SIGNATURE)
      .deterministic(true)
      .choice(choice -> choice
          .implementation(methodsGroup -> methodsGroup.methods("varcharToVarcharCreateSliceWithExtraParameterLength"))
          .implementation(methodsGroup -> methodsGroup
              .methods("varcharToBigintReturnExtraParameter")
              .withExtraParameters(context -> ImmutableList.of(42))))
      .build();
  ScalarFunctionImplementation functionImplementation = function.specialize(BOUND_VARIABLES, 1, TYPE_REGISTRY, REGISTRY);
  assertEquals(functionImplementation.getMethodHandle().invoke(INPUT_SLICE), VARCHAR_TO_BIGINT_RETURN_VALUE);
}

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

@Test
public void testSelectsMethodBasedOnArgumentTypes()
    throws Throwable
{
  SqlScalarFunction function = SqlScalarFunction.builder(TestMethods.class)
      .signature(SIGNATURE)
      .deterministic(true)
      .choice(choice -> choice
          .implementation(methodsGroup -> methodsGroup.methods("bigintToBigintReturnExtraParameter"))
          .implementation(methodsGroup -> methodsGroup
              .methods("varcharToBigintReturnExtraParameter")
              .withExtraParameters(context -> ImmutableList.of(context.getLiteral("x")))))
      .build();
  ScalarFunctionImplementation functionImplementation = function.specialize(BOUND_VARIABLES, 1, TYPE_REGISTRY, REGISTRY);
  assertEquals(functionImplementation.getMethodHandle().invoke(INPUT_SLICE), INPUT_VARCHAR_LENGTH);
}

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

@Test
public void testSameLiteralInArgumentsAndReturnValue()
    throws Throwable
{
  Signature signature = Signature.builder()
      .name("foo")
      .kind(SCALAR)
      .returnType(parseTypeSignature("varchar(x)", ImmutableSet.of("x")))
      .argumentTypes(parseTypeSignature("varchar(x)", ImmutableSet.of("x")))
      .build();
  SqlScalarFunction function = SqlScalarFunction.builder(TestMethods.class)
      .signature(signature)
      .deterministic(true)
      .choice(choice -> choice
          .implementation(methodsGroup -> methodsGroup.methods("varcharToVarchar")))
      .build();
  ScalarFunctionImplementation functionImplementation = function.specialize(BOUND_VARIABLES, 1, TYPE_REGISTRY, REGISTRY);
  Slice slice = (Slice) functionImplementation.getMethodHandle().invoke(INPUT_SLICE);
  assertEquals(slice, VARCHAR_TO_VARCHAR_RETURN_VALUE);
}

相关文章