当前位置: 首页>>代码示例>>Java>>正文


Java Reflection.newProxy方法代码示例

本文整理汇总了Java中com.google.common.reflect.Reflection.newProxy方法的典型用法代码示例。如果您正苦于以下问题:Java Reflection.newProxy方法的具体用法?Java Reflection.newProxy怎么用?Java Reflection.newProxy使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.common.reflect.Reflection的用法示例。


在下文中一共展示了Reflection.newProxy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: beanManager

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
@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());
    }
  });
}
 
开发者ID:jooby-project,项目名称:jooby,代码行数:19,代码来源:GuiceBeanManager.java

示例2: getDefaultValue

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
private static Object getDefaultValue(Class<?> returnType) {
  Object defaultValue = ArbitraryInstances.get(returnType);
  if (defaultValue != null) {
    return defaultValue;
  }
  if ("java.util.function.Predicate".equals(returnType.getCanonicalName())
      || ("java.util.function.Consumer".equals(returnType.getCanonicalName()))) {
    // 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(returnType, 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 ("test".equals(method.getName()) || "accept".equals(method.getName())) {
          return getDefaultValue(method.getReturnType());
        }
        throw new IllegalStateException("Unexpected " + method + " invoked on " + proxy);
      }
    });
  } else {
    return null;
  }
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:26,代码来源:ForwardingMapTest.java

示例3: put

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
public void put(final ModuleIdentifier moduleIdentifier, final Module module, final ModuleFactory moduleFactory,
        final ModuleInternalInfo maybeOldInternalInfo,
        final TransactionModuleJMXRegistration transactionModuleJMXRegistration, final boolean isDefaultBean,
        final BundleContext bundleContext) {
    transactionStatus.checkNotCommitted();

    Class<? extends Module> moduleClass = Module.class;
    if (module instanceof RuntimeBeanRegistratorAwareModule) {
        moduleClass = RuntimeBeanRegistratorAwareModule.class;
    }
    Module proxiedModule = Reflection.newProxy(moduleClass,
            new ModuleInvocationHandler(deadlockMonitor, moduleIdentifier, module));
    ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = new ModuleInternalTransactionalInfo(
            moduleIdentifier, proxiedModule, moduleFactory, maybeOldInternalInfo, transactionModuleJMXRegistration,
            isDefaultBean, module, bundleContext);
    modulesHolder.put(moduleInternalTransactionalInfo);
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:18,代码来源:DependencyResolverManager.java

示例4: createInstance

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
@Override
public AutoCloseable createInstance() {
    // The service is provided via blueprint so wait for and return it here for backwards compatibility.
    final WaitingServiceTracker<Timer> tracker = WaitingServiceTracker.create(
            Timer.class, bundleContext, "(type=global-timer)");
    final Timer timer = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES);

    return Reflection.newProxy(AutoCloseableTimerInterface.class, new AbstractInvocationHandler() {
        @Override
        protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable {
            if (method.getName().equals("close")) {
                tracker.close();
                return null;
            } else {
                return method.invoke(timer, args);
            }
        }
    });
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:20,代码来源:HashedWheelTimerModule.java

示例5: createInstance

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
@Override
public AutoCloseable createInstance() {
    // The service is provided via blueprint so wait for and return it here for backwards compatibility.
    String typeFilter = String.format("(type=%s)", getIdentifier().getInstanceName());
    final WaitingServiceTracker<EventLoopGroup> tracker = WaitingServiceTracker.create(
            EventLoopGroup.class, bundleContext, typeFilter);
    final EventLoopGroup group = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES);

    return Reflection.newProxy(AutoCloseableEventLoopGroupInterface.class, new AbstractInvocationHandler() {
        @Override
        protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable {
            if (method.getName().equals("close")) {
                tracker.close();
                return null;
            } else {
                return method.invoke(group, args);
            }
        }
    });
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:21,代码来源:NettyThreadgroupModule.java

示例6: setUp

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);

    dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.CONFIGURATION);
    dataTree.setSchemaContext(SCHEMA_CONTEXT);

    realModification = dataTree.takeSnapshot().newModification();
    proxyModification = Reflection.newProxy(DataTreeModification.class, (proxy, method, args) -> {
        try {
            method.invoke(mockModification, args);
            return method.invoke(realModification, args);
        } catch (InvocationTargetException e) {
            throw e.getCause();
        }
    });

    pruningDataTreeModification = new PruningDataTreeModification(proxyModification, dataTree, SCHEMA_CONTEXT);
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:20,代码来源:PruningDataTreeModificationTest.java

示例7: createInstance

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
@Override
public AutoCloseable createInstance() {
    final WaitingServiceTracker<EntityOwnershipService> tracker = WaitingServiceTracker.create(
            EntityOwnershipService.class, bundleContext);
    final EntityOwnershipService service = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES);

    return Reflection.newProxy(AutoCloseableEntityOwnershipService.class, new AbstractInvocationHandler() {
        @Override
        protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("close")) {
                tracker.close();
                return null;
            } else {
                try {
                    return method.invoke(service, args);
                } catch (InvocationTargetException e) {
                    // https://bugs.opendaylight.org/show_bug.cgi?id=6564
                    // http://stackoverflow.com/a/10719613/421602
                    // https://amitstechblog.wordpress.com/2011/07/24/java-proxies-and-undeclaredthrowableexception/
                    throw e.getCause();
                }
            }
        }
    });
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:26,代码来源:LegacyEntityOwnershipServiceProviderModule.java

示例8: createInstance

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
@Override
public AutoCloseable createInstance() {
    final WaitingServiceTracker<ClusterSingletonServiceProvider> tracker = WaitingServiceTracker
            .create(ClusterSingletonServiceProvider.class, bundleContext);
    final ClusterSingletonServiceProvider service = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES);

    // Create a proxy to override close to close the ServiceTracker. The actual DOMClusterSingletonServiceProvider
    // instance will be closed via blueprint.
    return Reflection.newProxy(AutoCloseableDOMClusterSingletonServiceProvider.class,
            new AbstractInvocationHandler() {
                @Override
                protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
                        throws Throwable {
                    if (method.getName().equals("close")) {
                        tracker.close();
                        return null;
                    } else {
                        return method.invoke(service, args);
                    }
                }
            });
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:23,代码来源:ClusterSingletonServiceProviderModule.java

示例9: newPartitionContextTest

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
public static <S> PartitionContextValidator<S> newPartitionContextTest(final Class<S> ifc, final Class<? extends S> impl) {
    final PartitionContextSupplier supplier = new AnnotationPartitionContextSupplier(ifc, impl);
    return new PartitionContextValidator<S>() {
        @Override
        public S expect(final PartitionContext expected) {
            return Reflection.newProxy(ifc, new AbstractInvocationHandler() {
                @Override
                protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
                    PartitionContext actual = supplier.forCall(method, args);
                    assertEquals(actual, expected, "Expected=" + expected.asMap() + ", Actual=" + actual.asMap());
                    return Defaults.defaultValue(method.getReturnType());
                }
            });
        }
    };
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:17,代码来源:OstrichAccessors.java

示例10: create

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
/**
 * Create new composite listener for a collection of delegates.
 */
@SafeVarargs
public static <T extends ParseTreeListener> T create(Class<T> type, T... delegates) {
    ImmutableList<T> listeners = ImmutableList.copyOf(delegates);
    return Reflection.newProxy(type, new AbstractInvocationHandler() {

        @Override
        @ParametersAreNonnullByDefault
        protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
            for (T listener : listeners) {
                method.invoke(listener, args);
            }
            return null;
        }

        @Override
        public String toString() {
            return MoreObjects.toStringHelper("CompositeParseTreeListener")
                    .add("listeners", listeners)
                    .toString();
        }
    });

}
 
开发者ID:protostuff,项目名称:protostuff-compiler,代码行数:27,代码来源:CompositeParseTreeListener.java

示例11: getObject

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
public T getObject() throws Exception {
  final T mapper = getSqlSession().getMapper(this.mapperInterface);

  return Reflection.newProxy(this.mapperInterface, new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      long start = System.currentTimeMillis();
      TraceContext rpc = TraceContext.get();
      String parameters = getParameters(args);
      String iface = MapperFactoryBean.this.iface;
      rpc.reset().inc().setStamp(start).setIface(iface).setMethod(method.getName()).setParameter(parameters);
      try {
        return method.invoke(mapper, args);
      } catch (Exception e) {
        rpc.setFail(true).setReason(e.getMessage());
        LOG.error("{}.{}({})", iface, method.getName(), parameters, e);
        throw e;
      } finally {
        rpc.setCost(System.currentTimeMillis() - start);
        TraceRecorder.getInstance().post(rpc.copy());
      }
    }
  });
}
 
开发者ID:colin-lee,项目名称:mybatis-spring-support,代码行数:28,代码来源:MapperFactoryBean.java

示例12: proxyInjector

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
@SuppressWarnings("rawtypes")
private static Injector proxyInjector(final ClassLoader loader, final Map<Key, Object> registry) {
  return Reflection.newProxy(Injector.class, (proxy, method, args) -> {
    if (method.getName().equals("getInstance")) {
      Key key = (Key) args[0];
      Object value = registry.get(key);
      if (value == null) {
        Object type = key.getAnnotation() != null ? key : key.getTypeLiteral();
        IllegalStateException iex = new IllegalStateException("Not found: " + type);
        // Skip proxy and some useless lines:
        Try.apply(() -> {
          StackTraceElement[] stacktrace = iex.getStackTrace();
          return Lists.newArrayList(stacktrace).subList(CLEAN_STACK, stacktrace.length);
        }).onSuccess(stacktrace -> iex
            .setStackTrace(stacktrace.toArray(new StackTraceElement[stacktrace.size()])));
        throw iex;
      }
      return value;
    }
    throw new UnsupportedOperationException(method.toString());
  });
}
 
开发者ID:jooby-project,项目名称:jooby,代码行数:23,代码来源:MockRouter.java

示例13: getName

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
/** Makes a fresh type variable that's only equal to itself. */
@SuppressWarnings("unchecked")  // Delegates to the <T> of class Var except getName().
static TypeVariable<Class<?>> freshTypeVariable(final String name) {
  // Use dynamic proxy so we only changes the behavior of getName() and equals/hashCode
  // Everything else delegates to a JDK native type variable.
  return Reflection.newProxy(TypeVariable.class, new AbstractInvocationHandler() {
    @Override protected Object handleInvocation(Object proxy, Method method, Object[] args)
        throws Throwable {
      if (method.getName().equals("getName")) {
        return name;
      }
      try {
        return method.invoke(PROTOTYPE, args);
      } catch (InvocationTargetException e) {
        throw e.getCause();
      }
    }
    @Override public String toString() { return name; }
  });
}
 
开发者ID:jparsec,项目名称:jparsec-g,代码行数:21,代码来源:Types.java

示例14: asVisitor

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
/** Transforms the given {@code UniformVisitor} into a {@code CssTreeVisitor}. */
public static CssTreeVisitor asVisitor(final UniformVisitor visitor) {
  return Reflection.newProxy(
      CssTreeVisitor.class,
      new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          // Allow methods from Object, like toString().
          if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(visitor, args);
          }

          CssNode node = (CssNode) args[0];
          if (method.getName().startsWith("enter")) {
            visitor.enter(node);
            return true; // Always visit children
          } else if (method.getName().startsWith("leave")) {
            visitor.leave(node);
            return null; // All leave* methods are void
          }
          throw new IllegalStateException("Unexpected method '" + method + "' called");
        }
      });
}
 
开发者ID:google,项目名称:closure-stylesheets,代码行数:25,代码来源:UniformVisitor.java

示例15: asCombinedVisitor

import com.google.common.reflect.Reflection; //导入方法依赖的package包/类
/**
 * Transforms the given visitor into a {@code CssTreeVisitor} that calls the {@code
 * UniformVisitor}'s {@code enter} method before each {@code enter*} method and its {@code
 * leave} method after each {@code leave*} method.
 */
public static <T extends UniformVisitor & CssTreeVisitor> CssTreeVisitor asCombinedVisitor(
    final T visitor) {
  return Reflection.newProxy(
      CssTreeVisitor.class,
      new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          // Allow methods from Object, like toString().
          if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(visitor, args);
          }

          CssNode node = (CssNode) args[0];
          if (method.getName().startsWith("enter")) {
            visitor.enter(node);
            return method.invoke(visitor, args);
          } else if (method.getName().startsWith("leave")) {
            Object result = method.invoke(visitor, args);
            visitor.leave(node);
            return result;
          }
          throw new IllegalStateException("Unexpected method '" + method + "' called");
        }
      });
}
 
开发者ID:google,项目名称:closure-stylesheets,代码行数:31,代码来源:UniformVisitor.java


注:本文中的com.google.common.reflect.Reflection.newProxy方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。