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

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

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

MethodHandle.invokeWithArguments介绍

[英]Performs a variable arity invocation, passing the arguments in the given array to the method handle, as if via an inexact #invoke from a call site which mentions only the type Object, and whose arity is the length of the argument array.

This method is also equivalent to the following code:

invokeWithArguments(arguments.toArray()

[中]执行变量arity调用,将给定数组中的参数传递给方法句柄,就像通过调用站点的不精确#调用一样,调用站点只提到类型对象,其arity是参数数组的长度。
此方法也相当于以下代码:

invokeWithArguments(arguments.toArray()

代码示例

代码示例来源:origin: org.codehaus.groovy/groovy

@Override
  public Object invokeHandle(Object handle, Object[] args) throws Throwable {
    MethodHandle mh = (MethodHandle) handle;
    return mh.invokeWithArguments(args);
  }
}

代码示例来源:origin: square/retrofit

@Override Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object,
  @Nullable Object... args) throws Throwable {
 // Because the service interface might not be public, we need to use a MethodHandle lookup
 // that ignores the visibility of the declaringClass.
 Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class, int.class);
 constructor.setAccessible(true);
 return constructor.newInstance(declaringClass, -1 /* trusted */)
   .unreflectSpecial(method, declaringClass)
   .bindTo(object)
   .invokeWithArguments(args);
}

代码示例来源:origin: org.objenesis/objenesis

@Override
 Class<?> defineClass(String className, byte[] b, int off, int len, Class<?> neighbor, ClassLoader loader, ProtectionDomain protectionDomain) {
   try {
    Object module = getModule.invokeWithArguments(DefineClassHelper.class);
    Object neighborModule = getModule.invokeWithArguments(neighbor);
    addReads.invokeWithArguments(module, neighborModule);
    MethodHandles.Lookup prvlookup = (MethodHandles.Lookup) privateLookupIn.invokeExact(neighbor, lookup);
    return (Class<?>) defineClass.invokeExact(prvlookup, b);
   } catch (Throwable e) {
    throw new ObjenesisException(neighbor.getName() + " has no permission to define the class", e);
   }
 }
}

代码示例来源:origin: baomidou/mybatis-plus

private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
  throws Throwable {
  final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
    .getDeclaredConstructor(Class.class, int.class);
  if (!constructor.isAccessible()) {
    constructor.setAccessible(true);
  }
  final Class<?> declaringClass = method.getDeclaringClass();
  return constructor
    .newInstance(declaringClass,
      MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
        | MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
    .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
}

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

static Object callDefaultMethod(Object proxy, Method method, Object[] args) throws Throwable
  {
    // Call the default method implementation - https://rmannibucau.wordpress.com/2014/03/27/java-8-default-interface-methods-and-jdk-dynamic-proxies/
    Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class);
    constructor.setAccessible(true);

    Class<?> declaringClass = method.getDeclaringClass();
    return constructor.newInstance(declaringClass, MethodHandles.Lookup.PUBLIC | MethodHandles.Lookup.PRIVATE)
      .unreflectSpecial(method, declaringClass)
      .bindTo(proxy)
      .invokeWithArguments(args);
  }
}

代码示例来源:origin: com.squareup.retrofit2/retrofit

@Override Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object,
  @Nullable Object... args) throws Throwable {
 // Because the service interface might not be public, we need to use a MethodHandle lookup
 // that ignores the visibility of the declaringClass.
 Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class, int.class);
 constructor.setAccessible(true);
 return constructor.newInstance(declaringClass, -1 /* trusted */)
   .unreflectSpecial(method, declaringClass)
   .bindTo(object)
   .invokeWithArguments(args);
}

代码示例来源:origin: org.javassist/javassist

@Override
  Package definePackage(ClassLoader loader, String name, String specTitle,
        String specVersion, String specVendor, String implTitle, String implVersion,
        String implVendor, URL sealBase)
    throws IllegalArgumentException
  {
    if (stack.getCallerClass() != DefinePackageHelper.class)
      throw new IllegalAccessError("Access denied for caller.");
    try {
      return (Package) definePackage.invokeWithArguments(loader, name, specTitle,
          specVersion, specVendor, implTitle, implVersion, implVendor, sealBase);
    } catch (Throwable e) {
      if (e instanceof IllegalArgumentException) throw (IllegalArgumentException) e;
      if (e instanceof RuntimeException) throw (RuntimeException) e;
    }
    return null;
  }
}

代码示例来源:origin: scouter-project/scouter

@Override
  Package definePackage(ClassLoader loader, String name, String specTitle,
        String specVersion, String specVendor, String implTitle, String implVersion,
        String implVendor, URL sealBase)
    throws IllegalArgumentException
  {
    if (stack.getCallerClass() != DefinePackageHelper.class)
      throw new IllegalAccessError("Access denied for caller.");
    try {
      return (Package) definePackage.invokeWithArguments(loader, name, specTitle,
          specVersion, specVendor, implTitle, implVersion, implVendor, sealBase);
    } catch (Throwable e) {
      if (e instanceof IllegalArgumentException) throw (IllegalArgumentException) e;
      if (e instanceof RuntimeException) throw (RuntimeException) e;
    }
    return null;
  }
}

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

private static <T extends SqlParser> Supplier<T> tryConstructor(Class<T> clazz, Object... args) {
    return () -> {
      try {
        Object[] nonNullArgs = Arrays.stream(args).filter(Objects::nonNull).toArray(Object[]::new);
        Class[] argClasses = Arrays.stream(nonNullArgs).map(Object::getClass).toArray(Class[]::new);
        MethodType type = MethodType.methodType(void.class, argClasses);
        return (T) MethodHandles.lookup().findConstructor(clazz, type).invokeWithArguments(nonNullArgs);
      } catch (NoSuchMethodException ignored) {
        return null;
      } catch (Throwable t) {
        throw Sneaky.throwAnyway(t);
      }
    };
  }
}

代码示例来源:origin: org.javassist/javassist

Class<?> defineClass(String name, byte[] b, int off, int len,
             ClassLoader loader, ProtectionDomain protectionDomain)
    throws ClassFormatError
  {
    try {
      if (getCallerClass.invoke(stack) != Java9.class)
        throw new IllegalAccessError("Access denied for caller.");
    } catch (Exception e) {
      throw new RuntimeException("cannot initialize", e);
    }
    try {
      return (Class<?>) defineClass.invokeWithArguments(
            sunMiscUnsafeTheUnsafe.theUnsafe,
            name, b, off, len, loader, protectionDomain);
    } catch (Throwable e) {
      if (e instanceof RuntimeException) throw (RuntimeException) e;
      if (e instanceof ClassFormatError) throw (ClassFormatError) e;
      throw new ClassFormatError(e.getMessage());
    }
  }
}

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

private static <T extends TemplateEngine> Supplier<T> tryConstructor(Class<T> clazz, Object... args) {
    return () -> {
      try {
        Object[] nonNullArgs = Arrays.stream(args).filter(Objects::nonNull).toArray(Object[]::new);
        Class[] argClasses = Arrays.stream(nonNullArgs).map(Object::getClass).toArray(Class[]::new);
        MethodType type = MethodType.methodType(void.class, argClasses);
        return (T) MethodHandles.lookup().findConstructor(clazz, type).invokeWithArguments(nonNullArgs);
      } catch (NoSuchMethodException ignored) {
        return null;
      } catch (Throwable t) {
        throw Sneaky.throwAnyway(t);
      }
    };
  }
}

代码示例来源:origin: oracle/helidon

public T create(Config configNode) {
  List<Object> args = createArguments(configNode);
  try {
    Object obj = handle.invokeWithArguments(args);
    return type.cast(obj);
  } catch (ConfigException ex) {
    throw ex;
  } catch (Throwable throwable) {
    throw new ConfigException("Unable to create '" + type.getName() + "' instance.", throwable);
  }
}

代码示例来源:origin: org.javassist/javassist

@Override
  Class<?> defineClass(String name, byte[] b, int off, int len, Class<?> neighbor,
      ClassLoader loader, ProtectionDomain protectionDomain)
    throws ClassFormatError
  {
    if (stack.getCallerClass() != DefineClassHelper.class)
      throw new IllegalAccessError("Access denied for caller.");
    try {
      return (Class<?>) defineClass.invokeWithArguments(
            loader, name, b, off, len, protectionDomain);
    } catch (Throwable e) {
      if (e instanceof RuntimeException) throw (RuntimeException) e;
      if (e instanceof ClassFormatError) throw (ClassFormatError) e;
      throw new ClassFormatError(e.getMessage());
    }
  }
}

代码示例来源:origin: scouter-project/scouter

@Override
  Class<?> defineClass(String name, byte[] b, int off, int len, Class<?> neighbor,
      ClassLoader loader, ProtectionDomain protectionDomain)
    throws ClassFormatError
  {
    if (stack.getCallerClass() != DefineClassHelper.class)
      throw new IllegalAccessError("Access denied for caller.");
    try {
      return (Class<?>) defineClass.invokeWithArguments(
            loader, name, b, off, len, protectionDomain);
    } catch (Throwable e) {
      if (e instanceof RuntimeException) throw (RuntimeException) e;
      if (e instanceof ClassFormatError) throw (ClassFormatError) e;
      throw new ClassFormatError(e.getMessage());
    }
  }
}

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

private static long getReferenceCountMapOverhead(TestComplexState state)
{
  long overhead = 0;
  // reflection is necessary because TestComplexState implementation is generated
  Field[] stateFields = state.getClass().getDeclaredFields();
  try {
    for (Field stateField : stateFields) {
      if (stateField.getType() != BlockBigArray.class && stateField.getType() != SliceBigArray.class) {
        continue;
      }
      stateField.setAccessible(true);
      Field[] bigArrayFields = stateField.getType().getDeclaredFields();
      for (Field bigArrayField : bigArrayFields) {
        if (bigArrayField.getType() != ReferenceCountMap.class) {
          continue;
        }
        bigArrayField.setAccessible(true);
        MethodHandle sizeOf = Reflection.methodHandle(bigArrayField.getType(), "sizeOf");
        overhead += (long) sizeOf.invokeWithArguments(bigArrayField.get(stateField.get(state)));
      }
    }
  }
  catch (Throwable t) {
    throw new RuntimeException(t);
  }
  return overhead;
}

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

@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
 private static <T> T invokeDynamic(
   Class<?> cls, String methodName, Class<?> returnType, ClassParameter<?>... params)
   throws Throwable {
  MethodType methodType =
    MethodType.methodType(
      returnType, Arrays.stream(params).map(param -> param.clazz).toArray(Class[]::new));
  CallSite callsite =
    InvokeDynamicSupport.bootstrapIntrinsic(
      MethodHandles.lookup(), methodName, methodType, cls.getName());
  return (T)
    callsite
      .dynamicInvoker()
      .invokeWithArguments(
        Arrays.stream(params).map(param -> param.val).collect(Collectors.toList()));
 }
}

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

private long getComplexStateRetainedSize(TestComplexState state)
{
  long retainedSize = ClassLayout.parseClass(state.getClass()).instanceSize();
  // reflection is necessary because TestComplexState implementation is generated
  Field[] fields = state.getClass().getDeclaredFields();
  try {
    for (Field field : fields) {
      Class type = field.getType();
      field.setAccessible(true);
      if (type == BlockBigArray.class || type == BooleanBigArray.class || type == SliceBigArray.class ||
          type == ByteBigArray.class || type == DoubleBigArray.class || type == LongBigArray.class || type == IntBigArray.class) {
        MethodHandle sizeOf = Reflection.methodHandle(type, "sizeOf");
        retainedSize += (long) sizeOf.invokeWithArguments(field.get(state));
      }
    }
  }
  catch (Throwable t) {
    throw new RuntimeException(t);
  }
  return retainedSize;
}

代码示例来源:origin: lettuce-io/lettuce-core

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  Method method = invocation.getMethod();
  if (!method.isDefault()) {
    return invocation.proceed();
  }
  LettuceAssert.isTrue(invocation instanceof InvocationTargetProvider,
      "Invocation must provide a target object via InvocationTargetProvider");
  InvocationTargetProvider targetProvider = (InvocationTargetProvider) invocation;
  return methodHandleCache.computeIfAbsent(method, DefaultMethodInvokingInterceptor::lookupMethodHandle)
      .bindTo(targetProvider.getInvocationTarget()).invokeWithArguments(invocation.getArguments());
}

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

return method.invokeWithArguments(actualArguments);

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

@Override
protected Object visitArithmeticUnary(ArithmeticUnaryExpression node, Object context)
{
  Object value = process(node.getValue(), context);
  if (value == null) {
    return null;
  }
  if (value instanceof Expression) {
    return new ArithmeticUnaryExpression(node.getSign(), toExpression(value, type(node.getValue())));
  }
  switch (node.getSign()) {
    case PLUS:
      return value;
    case MINUS:
      Signature operatorSignature = metadata.getFunctionRegistry().resolveOperator(OperatorType.NEGATION, types(node.getValue()));
      MethodHandle handle = metadata.getFunctionRegistry().getScalarFunctionImplementation(operatorSignature).getMethodHandle();
      if (handle.type().parameterCount() > 0 && handle.type().parameterType(0) == ConnectorSession.class) {
        handle = handle.bindTo(session);
      }
      try {
        return handle.invokeWithArguments(value);
      }
      catch (Throwable throwable) {
        throwIfInstanceOf(throwable, RuntimeException.class);
        throwIfInstanceOf(throwable, Error.class);
        throw new RuntimeException(throwable.getMessage(), throwable);
      }
  }
  throw new UnsupportedOperationException("Unsupported unary operator: " + node.getSign());
}

相关文章