com.google.common.reflect.Reflection.newProxy()方法的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(9.3k)|赞(0)|评价(0)|浏览(184)

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

Reflection.newProxy介绍

[英]Returns a proxy instance that implements interfaceType by dispatching method invocations to handler. The class loader of interfaceType will be used to define the proxy class. To implement multiple interfaces or specify a class loader, use Proxy#newProxyInstance.
[中]返回一个代理实例,该实例通过向处理程序分派方法调用来实现interfaceType。interfaceType的类加载器将用于定义代理类。要实现多个接口或指定类加载器,请使用Proxy#newProxyInstance。

代码示例

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

private <T> T newProxy(final Class<T> interfaceType) {
 return Reflection.newProxy(interfaceType, new FreshInvocationHandler(interfaceType));
}

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

void testInteraction(Function<? super T, ? extends T> wrapperFunction) {
 T proxy = Reflection.newProxy(interfaceType, this);
 T wrapper = wrapperFunction.apply(proxy);
 boolean isPossibleChainingCall = interfaceType.isAssignableFrom(method.getReturnType());
 try {
  Object actualReturnValue = method.invoke(wrapper, passedArgs);
  // If we think this might be a 'chaining' call then we allow the return value to either
  // be the wrapper or the returnValue.
  if (!isPossibleChainingCall || wrapper != actualReturnValue) {
   assertEquals(
     "Return value of " + method + " not forwarded", returnValue, actualReturnValue);
  }
 } catch (IllegalAccessException e) {
  throw new RuntimeException(e);
 } catch (InvocationTargetException e) {
  throw Throwables.propagate(e.getCause());
 }
 assertEquals("Failed to forward to " + method, 1, called.get());
}

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

private static <T> void testExceptionPropagation(
  Class<T> interfaceType, Method method, Function<? super T, ? extends T> wrapperFunction) {
 final RuntimeException exception = new RuntimeException();
 T proxy =
   Reflection.newProxy(
     interfaceType,
     new AbstractInvocationHandler() {
      @Override
      protected Object handleInvocation(Object p, Method m, Object[] args)
        throws Throwable {
       throw exception;
      }
     });
 T wrapper = wrapperFunction.apply(proxy);
 try {
  method.invoke(wrapper, getParameterValues(method));
  fail(method + " failed to throw exception as is.");
 } catch (InvocationTargetException e) {
  if (exception != e.getCause()) {
   throw new RuntimeException(e);
  }
 } catch (IllegalAccessException e) {
  throw new AssertionError(e);
 }
}

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

@Override
public void configure(Binder binder)
{
  // Install no-op session supplier on workers, since only coordinators create sessions.
  binder.bind(SessionSupplier.class).to(NoOpSessionSupplier.class).in(Scopes.SINGLETON);
  // Install no-op resource group manager on workers, since only coordinators manage resource groups.
  binder.bind(ResourceGroupManager.class).to(NoOpResourceGroupManager.class).in(Scopes.SINGLETON);
  // Install no-op transaction manager on workers, since only coordinators manage transactions.
  binder.bind(TransactionManager.class).to(NoOpTransactionManager.class).in(Scopes.SINGLETON);
  // Install no-op failure detector on workers, since only coordinators need global node selection.
  binder.bind(FailureDetector.class).to(NoOpFailureDetector.class).in(Scopes.SINGLETON);
  // HACK: this binding is needed by SystemConnectorModule, but will only be used on the coordinator
  binder.bind(QueryManager.class).toInstance(newProxy(QueryManager.class, (proxy, method, args) -> {
    throw new UnsupportedOperationException();
  }));
}

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

private static <T> T empty(final Class<T> type) {
 return Reflection.newProxy(type, (proxy, method, args) -> {
  throw new UnsupportedOperationException(method.toString());
 });
}

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

@SuppressWarnings("unchecked")
 private static <T> AnnotatedType<T> createAnnotatedType(final Class<T> type) {
  return Reflection.newProxy(AnnotatedType.class, (proxy, method, args) -> {
   if (method.getName().equals("getJavaClass")) {
    return type;
   }
   throw new UnsupportedOperationException(method.toString());
  });
 }
}

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

private static <D extends GenericDeclaration> TypeVariable<D> newTypeVariableImpl(
  D genericDeclaration, String name, Type[] bounds) {
 TypeVariableImpl<D> typeVariableImpl =
   new TypeVariableImpl<D>(genericDeclaration, name, bounds);
 @SuppressWarnings("unchecked")
 TypeVariable<D> typeVariable =
   Reflection.newProxy(
     TypeVariable.class, new TypeVariableInvocationHandler(typeVariableImpl));
 return typeVariable;
}

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

@SuppressWarnings("unchecked")
private static <T> CreationalContext<T> createCreationalContext() {
 return Reflection.newProxy(CreationalContext.class, (proxy, method, args) -> {
  if (method.getName().equals("release")) {
   return null;
  }
  throw new UnsupportedOperationException(method.toString());
 });
}

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

private Object newBeanInterface(final Request req, final Response rsp, final Route.Chain chain,
  final Class<?> beanType) {
 return Reflection.newProxy(beanType, (proxy, method, args) -> {
  StringBuilder name = new StringBuilder(method.getName()
    .replace("get", "")
    .replace("is", ""));
  name.setCharAt(0, Character.toLowerCase(name.charAt(0)));
  return value(new RequestParam(method, name.toString(), method.getGenericReturnType()), req,
    rsp, chain);
 });
}

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

public void testNewProxyCantWorkOnAClass() throws Exception {
 try {
  Reflection.newProxy(Object.class, X_RETURNER);
  fail();
 } catch (IllegalArgumentException expected) {
 }
}

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

public void testNewProxy() throws Exception {
 Runnable runnable = Reflection.newProxy(Runnable.class, X_RETURNER);
 assertEquals("x", runnable.toString());
}

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

@SuppressWarnings("unchecked") // proxy of Iterable<String>
private static Iterable<String> newDelegatingIterableWithEquals(Iterable<String> delegate) {
 return Reflection.newProxy(Iterable.class, new DelegatingInvocationHandlerWithEquals(delegate));
}

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

@SuppressWarnings("unchecked") // proxy of List<String>
private static List<String> newProxyWithSubHandler1(List<String> delegate) {
 return Reflection.newProxy(List.class, new SubHandler1(delegate));
}

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

@SuppressWarnings("unchecked") // proxy of List<String>
private static List<String> newProxyWithSubHandler2(List<String> delegate) {
 return Reflection.newProxy(List.class, new SubHandler2(delegate));
}

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

@SuppressWarnings("unchecked") // proxy of List<String>
private static List<String> newDelegatingList(List<String> delegate) {
 return Reflection.newProxy(List.class, new DelegatingInvocationHandler(delegate));
}

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

private static <D extends GenericDeclaration> TypeVariable<D> newTypeVariableImpl(
  D genericDeclaration, String name, Type[] bounds) {
 TypeVariableImpl<D> typeVariableImpl =
   new TypeVariableImpl<D>(genericDeclaration, name, bounds);
 @SuppressWarnings("unchecked")
 TypeVariable<D> typeVariable =
   Reflection.newProxy(
     TypeVariable.class, new TypeVariableInvocationHandler(typeVariableImpl));
 return typeVariable;
}

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

@SuppressWarnings("unchecked") // proxy of List<String>
private static List<String> newDelegatingListWithEquals(List<String> delegate) {
 return Reflection.newProxy(List.class, new DelegatingInvocationHandlerWithEquals(delegate));
}

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

private static <D extends GenericDeclaration> TypeVariable<D> newTypeVariableImpl(
  D genericDeclaration, String name, Type[] bounds) {
 TypeVariableImpl<D> typeVariableImpl =
   new TypeVariableImpl<D>(genericDeclaration, name, bounds);
 @SuppressWarnings("unchecked")
 TypeVariable<D> typeVariable =
   Reflection.newProxy(
     TypeVariable.class, new TypeVariableInvocationHandler(typeVariableImpl));
 return typeVariable;
}

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

private static Object getDefaultValue(final TypeToken<?> type) {
 Class<?> rawType = type.getRawType();
 Object defaultValue = ArbitraryInstances.get(rawType);
 if (defaultValue != null) {
  return defaultValue;
 }
 final String typeName = rawType.getCanonicalName();
 if (JUF_METHODS.containsKey(typeName)) {
  // Generally, methods that accept java.util.function.* instances
  // don't like to get null values.  We generate them dynamically
  // using Proxy so that we can have Java 7 compliant code.
  return Reflection.newProxy(
    rawType,
    new AbstractInvocationHandler() {
     @Override
     public Object handleInvocation(Object proxy, Method method, Object[] args) {
      // Crude, but acceptable until we can use Java 8.  Other
      // methods have default implementations, and it is hard to
      // distinguish.
      if (method.getName().equals(JUF_METHODS.get(typeName))) {
       return getDefaultValue(type.method(method).getReturnType());
      }
      throw new IllegalStateException("Unexpected " + method + " invoked on " + proxy);
     }
    });
 } else {
  return null;
 }
}

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

@SuppressWarnings({"unchecked", "rawtypes"})
public static BeanManager beanManager(final CompletableFuture<Registry> injector) {
 return Reflection.newProxy(BeanManager.class, (proxy, method, args) -> {
  final String name = method.getName();
  switch (name) {
   case "createAnnotatedType":
    return createAnnotatedType((Class) args[0]);
   case "createInjectionTarget":
    return createInjectionTarget(injector, ((AnnotatedType) args[0]).getJavaClass());
   case "createCreationalContext":
    return createCreationalContext();
   case "toString":
    return injector.toString();
   default:
    throw new UnsupportedOperationException(method.toString());
  }
 });
}

相关文章