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

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

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

Proxy.newProxyInstance介绍

[英]Returns an instance of the dynamically built class for the specified interfaces. Method invocations on the returned instance are forwarded to the specified invocation handler. The interfaces must be visible from the supplied class loader; no duplicates are permitted. All non-public interfaces must be defined in the same package.
[中]返回指定接口的动态生成类的实例。对返回实例的方法调用被转发到指定的调用处理程序。接口必须从提供的类加载器可见;不允许复制。所有非公共接口必须在同一个包中定义。

代码示例

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

private static <T> T newProxy(Class<T> interfaceType, InvocationHandler handler) {
 Object object =
   Proxy.newProxyInstance(
     interfaceType.getClassLoader(), new Class<?>[] {interfaceType}, handler);
 return interfaceType.cast(object);
}

代码示例来源:origin: spring-projects/spring-framework

private Object createInterfaceProxyForFactoryBean(final Object factoryBean, Class<?> interfaceType,
    final ConfigurableBeanFactory beanFactory, final String beanName) {
  return Proxy.newProxyInstance(
      factoryBean.getClass().getClassLoader(), new Class<?>[] {interfaceType},
      (proxy, method, args) -> {
        if (method.getName().equals("getObject") && args == null) {
          return beanFactory.getBean(beanName);
        }
        return ReflectionUtils.invokeMethod(method, factoryBean, args);
      });
}

代码示例来源:origin: spring-projects/spring-framework

static void visit(Object resource, InvocationHandler visitor) throws IOException {
  Object visitorProxy = Proxy.newProxyInstance(
      VIRTUAL_FILE_VISITOR_INTERFACE.getClassLoader(),
      new Class<?>[] {VIRTUAL_FILE_VISITOR_INTERFACE}, visitor);
  invokeVfsMethod(VIRTUAL_FILE_METHOD_VISIT, resource, visitorProxy);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void afterPropertiesSet() {
  if (this.serviceLocatorInterface == null) {
    throw new IllegalArgumentException("Property 'serviceLocatorInterface' is required");
  }
  // Create service locator proxy.
  this.proxy = Proxy.newProxyInstance(
      this.serviceLocatorInterface.getClassLoader(),
      new Class<?>[] {this.serviceLocatorInterface},
      new ServiceLocatorInvocationHandler());
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Wrap the given Connection with a proxy that delegates every method call to it
 * but suppresses close calls.
 * @param target the original Connection to wrap
 * @return the wrapped Connection
 */
protected Connection getCloseSuppressingConnectionProxy(Connection target) {
  return (Connection) Proxy.newProxyInstance(
      ConnectionProxy.class.getClassLoader(),
      new Class<?>[] {ConnectionProxy.class},
      new CloseSuppressingInvocationHandler(target));
}

代码示例来源:origin: apache/incubator-dubbo

@Override
@SuppressWarnings("unchecked")
public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
  return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new InvokerInvocationHandler(invoker));
}

代码示例来源:origin: apache/incubator-dubbo

@Override
@SuppressWarnings("unchecked")
public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
  return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new InvokerInvocationHandler(invoker));
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Create a close-suppressing proxy for the given Hibernate Session.
 * The proxy also prepares returned Query and Criteria objects.
 * @param session the Hibernate Session to create a proxy for
 * @return the Session proxy
 * @see Session#close()
 * @see #prepareQuery
 * @see #prepareCriteria
 */
protected Session createSessionProxy(Session session) {
  return (Session) Proxy.newProxyInstance(
      session.getClass().getClassLoader(), new Class<?>[] {Session.class},
      new CloseSuppressingInvocationHandler(session));
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Wrap the given Connection with a proxy that delegates every method call to it
 * but suppresses close calls. This is useful for allowing application code to
 * handle a special framework Connection just like an ordinary Connection from a
 * CCI ConnectionFactory.
 * @param target the original Connection to wrap
 * @return the wrapped Connection
 */
protected Connection getCloseSuppressingConnectionProxy(Connection target) {
  return (Connection) Proxy.newProxyInstance(
      Connection.class.getClassLoader(),
      new Class<?>[] {Connection.class},
      new CloseSuppressingInvocationHandler(target));
}

代码示例来源: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: spring-projects/spring-framework

private Session getCloseSuppressingSessionProxy(Session target) {
    List<Class<?>> classes = new ArrayList<>(3);
    classes.add(SessionProxy.class);
    if (target instanceof QueueSession) {
      classes.add(QueueSession.class);
    }
    if (target instanceof TopicSession) {
      classes.add(TopicSession.class);
    }
    return (Session) Proxy.newProxyInstance(SessionProxy.class.getClassLoader(),
        ClassUtils.toClassArray(classes), new CloseSuppressingSessionInvocationHandler(target));
  }
}

代码示例来源:origin: spring-projects/spring-framework

@SuppressWarnings("unchecked")
  public <T> T createMock(Class<T> toMock) {
    return (T) Proxy.newProxyInstance(BeanFactoryGenericsTests.class.getClassLoader(), new Class<?>[] {toMock},
        new InvocationHandler() {
          @Override
          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            throw new UnsupportedOperationException("mocked!");
          }
        });
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public ITestBean getObject() {
  return (ITestBean) Proxy.newProxyInstance(CustomProxyFactoryBean.class.getClassLoader(), new Class<?>[]{ITestBean.class}, new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      return ReflectionUtils.invokeMethod(method, tb, args);
    }
  });
}

代码示例来源:origin: spring-projects/spring-framework

@SuppressWarnings("unchecked")
  public <T> T createMock(Class<T> toMock) {
    return (T) Proxy.newProxyInstance(AutowiredAnnotationBeanPostProcessorTests.class.getClassLoader(), new Class<?>[] {toMock},
        new InvocationHandler() {
          @Override
          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            throw new UnsupportedOperationException("mocked!");
          }
        });
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
  if (logger.isTraceEnabled()) {
    logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
  }
  Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
  findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
  return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}

代码示例来源:origin: apache/incubator-dubbo

private Object buildProxy(String referencedBeanName, ReferenceBean referenceBean, Class<?> injectedType) {
  InvocationHandler handler = buildInvocationHandler(referencedBeanName, referenceBean);
  Object proxy = Proxy.newProxyInstance(getClassLoader(), new Class[]{injectedType}, handler);
  return proxy;
}

代码示例来源:origin: apache/incubator-dubbo

private Object buildProxy(String referencedBeanName, ReferenceBean referenceBean, Class<?> injectedType) {
  InvocationHandler handler = buildInvocationHandler(referencedBeanName, referenceBean);
  Object proxy = Proxy.newProxyInstance(getClassLoader(), new Class[]{injectedType}, handler);
  return proxy;
}

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

private static Object newProxyWithEqualsForInterfaces(Class<?>... interfaces) {
 return Proxy.newProxyInstance(
   AbstractInvocationHandlerTest.class.getClassLoader(),
   interfaces,
   new DelegatingInvocationHandlerWithEquals("a string"));
}

代码示例来源:origin: spring-projects/spring-framework

@Test(expected = IllegalArgumentException.class)
public void testProxiedUserInterfacesWithNoInterface() {
  Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[0],
      (proxy1, method, args) -> null);
  AopProxyUtils.proxiedUserInterfaces(proxy);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void varargsAgainstProxy_SPR16122() {
  SpelExpressionParser parser = new SpelExpressionParser();
  Expression expr = parser.parseExpression("process('a', 'b')");
  VarargsReceiver receiver = new VarargsReceiver();
  VarargsInterface proxy = (VarargsInterface) Proxy.newProxyInstance(
      getClass().getClassLoader(), new Class<?>[] {VarargsInterface.class},
      (proxy1, method, args) -> method.invoke(receiver, args));
  assertEquals("OK", expr.getValue(new StandardEvaluationContext(receiver)));
  assertEquals("OK", expr.getValue(new StandardEvaluationContext(proxy)));
}

相关文章