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

x33g5p2x  于2022-01-16 转载在 其他  
字(8.7k)|赞(0)|评价(0)|浏览(323)

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

Method.invoke介绍

[英]Invokes the underlying method represented by this Methodobject, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.

If the underlying method is static, then the specified objargument is ignored. It may be null.

If the number of formal parameters required by the underlying method is 0, the supplied args array may be of length 0 or null.

If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, Second Edition, section 15.12.4.4; in particular, overriding based on the runtime type of the target object will occur.

If the underlying method is static, the class that declared the method is initialized if it has not already been initialized.

If the method completes normally, the value it returns is returned to the caller of invoke; if the value has a primitive type, it is first appropriately wrapped in an object. However, if the value has the type of an array of a primitive type, the elements of the array are not wrapped in objects; in other words, an array of primitive type is returned. If the underlying method return type is void, the invocation returns null.
[中]在具有指定参数的指定对象上调用此Methodobject表示的基础方法。单个参数会自动展开以匹配基元形式参数,基元参数和引用参数都会根据需要进行方法调用转换。
如果基础方法是静态的,则忽略指定的objargument。它可能是空的。
如果基础方法所需的形式参数数为0,则提供的args数组的长度可能为0或null。
如果基础方法是实例方法,则使用Java语言规范第二版第15.12.4.4节中记录的动态方法查找来调用它;特别是,将发生基于目标对象的运行时类型的重写。
如果基础方法是静态的,则声明该方法的类将在尚未初始化时初始化。
如果方法正常完成,它返回的值将返回给invoke的调用者;如果该值具有基元类型,则首先将其适当地包装在对象中。但是,如果该值的类型为基元类型的数组,则该数组的元素不会包装在对象中;换句话说,返回一个基元类型的数组。如果基础方法返回类型为void,则调用将返回null。

代码示例

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

public static void addSuppressedIfPossible(Throwable e, Throwable suppressed) {
 if (addSuppressedExceptionMethod != null) {
  try {
   addSuppressedExceptionMethod.invoke(e, suppressed);
  } catch (InvocationTargetException | IllegalAccessException ignored) {
  }
 }
}

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

Object createAndOpen(String closer) {
 if (getMethod != null) {
  try {
   Object closeGuardInstance = getMethod.invoke(null);
   openMethod.invoke(closeGuardInstance, closer);
   return closeGuardInstance;
  } catch (Exception ignored) {
  }
 }
 return null;
}

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

boolean warnIfOpen(Object closeGuardInstance) {
 boolean reported = false;
 if (closeGuardInstance != null) {
  try {
   warnIfOpenMethod.invoke(closeGuardInstance);
   reported = true;
  } catch (Exception ignored) {
  }
 }
 return reported;
}

代码示例来源:origin: stackoverflow.com

Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);

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

@Override public void afterHandshake(SSLSocket sslSocket) {
 try {
  removeMethod.invoke(null, sslSocket);
 } catch (IllegalAccessException | InvocationTargetException e) {
  throw new AssertionError("failed to remove ALPN", e);
 }
}

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

@Override public @Nullable String getSelectedProtocol(SSLSocket socket) {
 try {
  byte[] alpnResult = (byte[]) getAlpnSelectedProtocol.invoke(socket);
  return alpnResult != null ? new String(alpnResult, UTF_8) : null;
 } catch (IllegalAccessException | InvocationTargetException e) {
  throw new AssertionError(e);
 }
}

代码示例来源:origin: google/guava

@Override
 String typeName(Type type) {
  try {
   Method getTypeName = Type.class.getMethod("getTypeName");
   return (String) getTypeName.invoke(type);
  } catch (NoSuchMethodException e) {
   throw new AssertionError("Type.getTypeName should be available in Java 8");
  } catch (InvocationTargetException | IllegalAccessException e) {
   throw new RuntimeException(e);
  }
 }
},

代码示例来源:origin: google/guava

private Object invokeGeneratorMethod(Method generator, Object... args) {
 try {
  return generator.invoke(this, args);
 } catch (InvocationTargetException e) {
  throwIfUnchecked(e.getCause());
  throw new RuntimeException(e.getCause());
 } catch (Exception e) {
  throwIfUnchecked(e);
  throw new RuntimeException(e);
 }
}

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

private boolean api24IsCleartextTrafficPermitted(String hostname, Class<?> networkPolicyClass,
  Object networkSecurityPolicy) throws InvocationTargetException, IllegalAccessException {
 try {
  Method isCleartextTrafficPermittedMethod = networkPolicyClass
    .getMethod("isCleartextTrafficPermitted", String.class);
  return (boolean) isCleartextTrafficPermittedMethod.invoke(networkSecurityPolicy, hostname);
 } catch (NoSuchMethodException e) {
  return api23IsCleartextTrafficPermitted(hostname, networkPolicyClass, networkSecurityPolicy);
 }
}

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

private boolean api23IsCleartextTrafficPermitted(String hostname, Class<?> networkPolicyClass,
  Object networkSecurityPolicy) throws InvocationTargetException, IllegalAccessException {
 try {
  Method isCleartextTrafficPermittedMethod = networkPolicyClass
    .getMethod("isCleartextTrafficPermitted");
  return (boolean) isCleartextTrafficPermittedMethod.invoke(networkSecurityPolicy);
 } catch (NoSuchMethodException e) {
  return super.isCleartextTrafficPermitted(hostname);
 }
}

代码示例来源:origin: google/guava

@Override
final Object invokeInternal(@Nullable Object receiver, Object[] args)
  throws InvocationTargetException, IllegalAccessException {
 return method.invoke(receiver, args);
}

代码示例来源:origin: google/guava

@GwtIncompatible // java.lang.reflect
private static Object invokeAccessibleNonThrowingMethod(
  Method method, Object receiver, Object... params) {
 try {
  return method.invoke(receiver, params);
 } catch (IllegalAccessException e) {
  throw new RuntimeException(e);
 } catch (InvocationTargetException e) {
  throw propagate(e.getCause());
 }
}

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

@Override public boolean isCleartextTrafficPermitted(String hostname) {
 try {
  Class<?> networkPolicyClass = Class.forName("android.security.NetworkSecurityPolicy");
  Method getInstanceMethod = networkPolicyClass.getMethod("getInstance");
  Object networkSecurityPolicy = getInstanceMethod.invoke(null);
  return api24IsCleartextTrafficPermitted(hostname, networkPolicyClass, networkSecurityPolicy);
 } catch (ClassNotFoundException | NoSuchMethodException e) {
  return super.isCleartextTrafficPermitted(hostname);
 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  throw new AssertionError("unable to determine cleartext support", e);
 }
}

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

@Override public void configureTlsExtensions(
  SSLSocket sslSocket, String hostname, List<Protocol> protocols) {
 List<String> names = alpnProtocolNames(protocols);
 try {
  Object alpnProvider = Proxy.newProxyInstance(Platform.class.getClassLoader(),
    new Class[] {clientProviderClass, serverProviderClass}, new AlpnProvider(names));
  putMethod.invoke(null, sslSocket, alpnProvider);
 } catch (InvocationTargetException | IllegalAccessException e) {
  throw new AssertionError("failed to set ALPN", e);
 }
}

代码示例来源:origin: google/guava

private Throwable tryInternalFastPathGetFailure(Future<?> future) throws Exception {
  Method tryInternalFastPathGetFailureMethod =
    abstractFutureClass.getDeclaredMethod("tryInternalFastPathGetFailure");
  tryInternalFastPathGetFailureMethod.setAccessible(true);
  return (Throwable) tryInternalFastPathGetFailureMethod.invoke(future);
 }
}

代码示例来源:origin: google/guava

private void runTestMethod(ClassLoader classLoader) throws Exception {
 Class<?> test = classLoader.loadClass(FuturesTest.class.getName());
 Object testInstance = test.newInstance();
 test.getMethod("setUp").invoke(testInstance);
 test.getMethod(getName()).invoke(testInstance);
 test.getMethod("tearDown").invoke(testInstance);
}

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

@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
   throws Throwable {
  // If the method is a method from Object then defer to normal invocation.
  if (method.getDeclaringClass() == Object.class) {
   return method.invoke(this, args);
  }
  if (platform.isDefaultMethod(method)) {
   return platform.invokeDefaultMethod(method, service, proxy, args);
  }
  return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
 }
});

代码示例来源:origin: google/guava

private static void doTestMocking(RateLimiter mock) throws Exception {
 for (Method method : RateLimiter.class.getMethods()) {
  if (!isStatic(method.getModifiers())
    && !NOT_WORKING_ON_MOCKS.contains(method.getName())
    && !method.getDeclaringClass().equals(Object.class)) {
   method.invoke(mock, arbitraryParameters(method));
  }
 }
}

代码示例来源:origin: google/guava

private Object invokeListMethod(Method method, Object[] args) throws Throwable {
 try {
  Object returnValue = method.invoke(delegate, args);
  mutateDelegate();
  return returnValue;
 } catch (InvocationTargetException e) {
  throw e.getCause();
 } catch (IllegalAccessException e) {
  throw new AssertionError(e);
 }
}

代码示例来源:origin: google/guava

@AndroidIncompatible // no FpUtils and no Math.nextDown in old versions
public void testNextDown() throws Exception {
 Method jdkNextDown = getJdkNextDown();
 for (double d : FINITE_DOUBLE_CANDIDATES) {
  assertEquals(jdkNextDown.invoke(null, d), DoubleUtils.nextDown(d));
 }
}

相关文章

微信公众号

最新文章

更多