Java 类com.google.common.reflect.Reflection 实例源码

项目:guava-mock    文件:NullPointerTester.java   
private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
  // Don't use cls.getPackage() because it does nasty things like reading
  // a file.
  String visiblePackage = Reflection.getPackageName(cls);
  ImmutableList.Builder<Method> builder = ImmutableList.builder();
  for (Class<?> type : TypeToken.of(cls).getTypes().rawTypes()) {
    if (!Reflection.getPackageName(type).equals(visiblePackage)) {
      break;
    }
    for (Method method : type.getDeclaredMethods()) {
      if (!method.isSynthetic() && isVisible(method)) {
        builder.add(method);
      }
    }
  }
  return builder.build();
}
项目:guava-mock    文件:ClassSanityTester.java   
/**
 * Tests null checks against the instance methods of the return values, if any.
 *
 * <p>Test fails if default value cannot be determined for a constructor or factory method
 * parameter, or if the constructor or factory method throws exception.
 *
 * @return this tester
 */
public FactoryMethodReturnValueTester testNulls() throws Exception {
  for (Invokable<?, ?> factory : getFactoriesToTest()) {
    Object instance = instantiate(factory);
    if (instance != null
        && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) {
      try {
        nullPointerTester.testAllPublicInstanceMethods(instance);
      } catch (AssertionError e) {
        AssertionError error = new AssertionFailedError(
            "Null check failed on return value of " + factory);
        error.initCause(e);
        throw error;
      }
    }
  }
  return this;
}
项目:guava-mock    文件:ForwardingMapTest.java   
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;
  }
}
项目:googles-monorepo-demo    文件:NullPointerTester.java   
private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
  // Don't use cls.getPackage() because it does nasty things like reading
  // a file.
  String visiblePackage = Reflection.getPackageName(cls);
  ImmutableList.Builder<Method> builder = ImmutableList.builder();
  for (Class<?> type : TypeToken.of(cls).getTypes().rawTypes()) {
    if (!Reflection.getPackageName(type).equals(visiblePackage)) {
      break;
    }
    for (Method method : type.getDeclaredMethods()) {
      if (!method.isSynthetic() && isVisible(method)) {
        builder.add(method);
      }
    }
  }
  return builder.build();
}
项目:googles-monorepo-demo    文件:ClassSanityTester.java   
/**
 * Tests null checks against the instance methods of the return values, if any.
 *
 * <p>Test fails if default value cannot be determined for a constructor or factory method
 * parameter, or if the constructor or factory method throws exception.
 *
 * @return this tester
 */
public FactoryMethodReturnValueTester testNulls() throws Exception {
  for (Invokable<?, ?> factory : getFactoriesToTest()) {
    Object instance = instantiate(factory);
    if (instance != null
        && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) {
      try {
        nullPointerTester.testAllPublicInstanceMethods(instance);
      } catch (AssertionError e) {
        AssertionError error = new AssertionFailedError(
            "Null check failed on return value of " + factory);
        error.initCause(e);
        throw error;
      }
    }
  }
  return this;
}
项目:googles-monorepo-demo    文件:ForwardingMapTest.java   
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;
  }
}
项目:hashsdn-controller    文件:DependencyResolverManager.java   
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);
}
项目:hashsdn-controller    文件:HashedWheelTimerModule.java   
@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);
            }
        }
    });
}
项目:hashsdn-controller    文件:NettyThreadgroupModule.java   
@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);
            }
        }
    });
}
项目:hashsdn-controller    文件:PruningDataTreeModificationTest.java   
@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);
}
项目:hashsdn-controller    文件:LegacyEntityOwnershipServiceProviderModule.java   
@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();
                }
            }
        }
    });
}
项目:hashsdn-controller    文件:ClusterSingletonServiceProviderModule.java   
@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);
                    }
                }
            });
}
项目:emodb    文件:OstrichAccessors.java   
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());
                }
            });
        }
    };
}
项目:protostuff-compiler    文件:CompositeParseTreeListener.java   
/**
 * 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();
        }
    });

}
项目:mybatis-spring-support    文件:MapperFactoryBean.java   
/**
 * {@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());
      }
    }
  });
}
项目:guava-libraries    文件:NullPointerTester.java   
private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
  // Don't use cls.getPackage() because it does nasty things like reading
  // a file.
  String visiblePackage = Reflection.getPackageName(cls);
  ImmutableList.Builder<Method> builder = ImmutableList.builder();
  for (Class<?> type : TypeToken.of(cls).getTypes().classes().rawTypes()) {
    if (!Reflection.getPackageName(type).equals(visiblePackage)) {
      break;
    }
    for (Method method : type.getDeclaredMethods()) {
      if (!method.isSynthetic() && isVisible(method)) {
        builder.add(method);
      }
    }
  }
  return builder.build();
}
项目:guava-libraries    文件:ClassSanityTester.java   
/**
 * Tests null checks against the instance methods of the return values, if any.
 *
 * <p>Test fails if default value cannot be determined for a constructor or factory method
 * parameter, or if the constructor or factory method throws exception.
 *
 * @return this tester
 */
public FactoryMethodReturnValueTester testNulls() throws Exception {
  for (Invokable<?, ?> factory : getFactoriesToTest()) {
    Object instance = instantiate(factory);
    if (instance != null
        && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) {
      try {
        nullPointerTester.testAllPublicInstanceMethods(instance);
      } catch (AssertionError e) {
        AssertionError error = new AssertionFailedError(
            "Null check failed on return value of " + factory);
        error.initCause(e);
        throw error;
      }
    }
  }
  return this;
}
项目:guava    文件:NullPointerTester.java   
private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
  // Don't use cls.getPackage() because it does nasty things like reading
  // a file.
  String visiblePackage = Reflection.getPackageName(cls);
  ImmutableList.Builder<Method> builder = ImmutableList.builder();
  for (Class<?> type : TypeToken.of(cls).getTypes().rawTypes()) {
    if (!Reflection.getPackageName(type).equals(visiblePackage)) {
      break;
    }
    for (Method method : type.getDeclaredMethods()) {
      if (!method.isSynthetic() && isVisible(method)) {
        builder.add(method);
      }
    }
  }
  return builder.build();
}
项目:guava    文件:ClassSanityTester.java   
/**
 * Tests null checks against the instance methods of the return values, if any.
 *
 * <p>Test fails if default value cannot be determined for a constructor or factory method
 * parameter, or if the constructor or factory method throws exception.
 *
 * @return this tester
 */
public FactoryMethodReturnValueTester testNulls() throws Exception {
  for (Invokable<?, ?> factory : getFactoriesToTest()) {
    Object instance = instantiate(factory);
    if (instance != null
        && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) {
      try {
        nullPointerTester.testAllPublicInstanceMethods(instance);
      } catch (AssertionError e) {
        AssertionError error =
            new AssertionFailedError("Null check failed on return value of " + factory);
        error.initCause(e);
        throw error;
      }
    }
  }
  return this;
}
项目:guava    文件:NullPointerTester.java   
private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
  // Don't use cls.getPackage() because it does nasty things like reading
  // a file.
  String visiblePackage = Reflection.getPackageName(cls);
  ImmutableList.Builder<Method> builder = ImmutableList.builder();
  for (Class<?> type : TypeToken.of(cls).getTypes().rawTypes()) {
    if (!Reflection.getPackageName(type).equals(visiblePackage)) {
      break;
    }
    for (Method method : type.getDeclaredMethods()) {
      if (!method.isSynthetic() && isVisible(method)) {
        builder.add(method);
      }
    }
  }
  return builder.build();
}
项目:guava    文件:ClassSanityTester.java   
/**
 * Tests null checks against the instance methods of the return values, if any.
 *
 * <p>Test fails if default value cannot be determined for a constructor or factory method
 * parameter, or if the constructor or factory method throws exception.
 *
 * @return this tester
 */
public FactoryMethodReturnValueTester testNulls() throws Exception {
  for (Invokable<?, ?> factory : getFactoriesToTest()) {
    Object instance = instantiate(factory);
    if (instance != null
        && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) {
      try {
        nullPointerTester.testAllPublicInstanceMethods(instance);
      } catch (AssertionError e) {
        AssertionError error =
            new AssertionFailedError("Null check failed on return value of " + factory);
        error.initCause(e);
        throw error;
      }
    }
  }
  return this;
}
项目:jparsec-g    文件:Types.java   
/** 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; }
  });
}
项目:magenta    文件:FixtureFieldHandler.java   
@Override
public boolean handle(Field f, Object target, Supplier<Fixture<S>> context) {
  if (f.isAnnotationPresent(org.magenta.annotations.InjectFixture.class)) {

    InjectFixture annotation = f.getAnnotation(org.magenta.annotations.InjectFixture.class);

    if (Fixture.class.equals(f.getType())) {
      Fixture proxy = Reflection.newProxy(Fixture.class, handler(context));
      FieldInjectorUtils.injectInto(target, f, proxy);
      return true;
    } else {
      throw new IllegalStateException("Annotation " + InjectFixture.class.getName() + " is present on field named " + f.getName()
          + ", but this field type is not a " + Fixture.class.getName());
    }
  } else {
    return false;
  }
}
项目:closure-stylesheets    文件:UniformVisitor.java   
/** 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");
        }
      });
}
项目:closure-stylesheets    文件:UniformVisitor.java   
/**
 * 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");
        }
      });
}
项目:jooby    文件:GuiceBeanManager.java   
@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());
    }
  });
}
项目:jooby    文件:GuiceBeanManager.java   
@SuppressWarnings("unchecked")
private static <T> InjectionTarget<T> createInjectionTarget(
  final CompletableFuture<Registry> injector, final Class<T> type) {
  return Reflection.newProxy(InjectionTarget.class, (proxy, method, args) -> {
    final String name = method.getName();
    switch (name) {
      case "produce":
        return injector.get().require(type);
      case "inject":
        return null;
      case "postConstruct":
        return null;
      case "preDestroy":
        return null;
      case "dispose":
        return null;
      default:
        throw new UnsupportedOperationException(method.toString());
    }
  });
}
项目:jooby    文件:MockRouter.java   
@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());
  });
}
项目:SevenCommons    文件:SevenCommons.java   
public void universalPreInit(FMLPreInitializationEvent event) {
    Configuration config = new Configuration(event.getSuggestedConfigurationFile());

    packets = Network.newChannel("SevenCommons")
            .register(PacketSync.class, SYNC_PACKET_ID)
            .register(PacketInventoryName.class)
            .register(PacketContainerButton.class)
            .build();

    ClassInfoUtil.preInit();

    // initialize the lazy statics in the scheduler class
    Reflection.initialize(Scheduler.class);

    TickRegistry.registerTickHandler(new SCPlayerTicker(), Side.SERVER);
    GameRegistry.registerPlayerTracker(new SCPlayerTracker());

    proxy.preInit(event);

    Syncing.registerFactory(Object.class, new BuiltinSyncers());
    ToNbtFactories.registerFactory(Object.class, new DefaultNBTSerializers());
}
项目:SevenCommons    文件:SCReflection.java   
/**
 * <p>Define a new Class specified by the given bytes.</p>
 *
 * @param bytes the bytes describing the class
 * @param context the class which to use as the context
 * @return the defined class
 */
public static Class<?> defineDynamicClass(byte[] bytes, Class<?> context) {
    if (DEBUG) {
        try {
            ClassNode node = ASMUtils.getThinClassNode(bytes);
            File file = new File("sevencommonsdyn/" + node.name + ".class");
            Files.createParentDirs(file);
            OutputStream out = new FileOutputStream(file);
            out.write(bytes);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
       ClassLoader cl = context.getClassLoader();
       Class<?> clazz;
       try {
           clazz = (Class<?>) CLASS_LOADER_DEFINE.invokeExact(cl, (String) null, bytes, 0, bytes.length);
       } catch (Throwable t) {
           throw Throwables.propagate(t);
       }
       Reflection.initialize(clazz);
       return clazz;
   }
项目:tellets    文件:CollectModule.java   
@SneakyThrows
protected void configure()
{
    // 初始化 Provider
    SourceProviderManager provider = instance(SourceProviderManager.class);

    // 包扫描所有已经实现的Provider
    ImmutableSet<Class<SourceProvider>> plugins = new PluginLoader<>(SourceProvider.class, Reflection
            .getPackageName(SourceProvider.class), ClassLoader.getSystemClassLoader())
            .getPlugins();

    for (Class<SourceProvider> clazz : Iterables.filter(plugins, annotatedBy(Enabled.class)))
    {
        provider.addProvider(instance(clazz));
    }

    // 绑定 Service
    DefaultCollectionService service = new DefaultCollectionService(provider);
    bind(CollectionService.class).toInstance(service);
}
项目:googleads-java-lib    文件:AdWordsServicesWithRateLimiter.java   
/**
 * Decide whether this RateLimiter extension is applicable to the original service / utility
 * object. If so, wrap it in a proxy object with rate-limit-aware invocation handle; if not, just
 * return the original object.
 */
private <T> T getProxyObject(
    T originalObject, AdWordsSession session, Class<T> cls, boolean isUtility) {
  // Find the retry strategy of this class type.
  ApiRetryStrategy retryStrategy =
      ApiRetryStrategyManager.getRetryStrategy(cls.getSimpleName(), isUtility);

  // If no corresponding retry strategy, just use the original object instead of a wrapping proxy.
  if (retryStrategy == null) {
    return originalObject;
  }

  InvocationHandler invocationHandler =
      new ApiInvocationHandlerWithRateLimiter(originalObject, session, retryStrategy);
  return Reflection.newProxy(cls, invocationHandler);
}
项目:TakinRPC    文件:ProxyFactory.java   
/**
 * 
 * @param strUrl  连接字符串
 * @param interfaceClass  接口类
 * @return
 */
private static Object createStandardProxy(Class<?> interfaceclass, String serviceName, Class<?> implMethod, LoadBalance balance) {
    InvocationHandler handler = new ProxyStandard(interfaceclass, serviceName, implMethod, balance);
    //        Object obj = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { interfaceclass }, handler);
    Object obj = Reflection.newProxy(interfaceclass, handler);
    logger.info(String.format("create jdkproxy for %s ", interfaceclass.getName()));
    return obj;
}
项目:guava-mock    文件:ClassSanityTester.java   
private FactoryMethodReturnValueTester(
    Class<?> declaringClass,
    ImmutableList<Invokable<?, ?>> factories,
    String factoryMethodsDescription) {
  this.declaringClass = declaringClass;
  this.factories = factories;
  this.factoryMethodsDescription = factoryMethodsDescription;
  packagesToTest.add(Reflection.getPackageName(declaringClass));
}
项目:googles-monorepo-demo    文件:ClassSanityTester.java   
private FactoryMethodReturnValueTester(
    Class<?> declaringClass,
    ImmutableList<Invokable<?, ?>> factories,
    String factoryMethodsDescription) {
  this.declaringClass = declaringClass;
  this.factories = factories;
  this.factoryMethodsDescription = factoryMethodsDescription;
  packagesToTest.add(Reflection.getPackageName(declaringClass));
}
项目:hashsdn-controller    文件:AutoCloseableEventExecutor.java   
private static AutoCloseableEventExecutor createCloseableProxy(
        final CloseableEventExecutorMixin closeableEventExecutorMixin) {
    return Reflection.newProxy(AutoCloseableEventExecutor.class, new AbstractInvocationHandler() {
        @Override
        protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable {
            if (method.getName().equals("close")) {
                closeableEventExecutorMixin.close();
                return null;
            } else {
                return method.invoke(closeableEventExecutorMixin.eventExecutor, args);
            }
        }
    });
}
项目:emodb    文件:PartitionAwareServiceFactory.java   
private S createDelegate(ServiceEndPoint endPoint) {
    final S delegateService = _delegate.create(endPoint);

    S proxiedService = Reflection.newProxy(_serviceClass, new AbstractInvocationHandler() {
        @Override
        protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
            try {
                return method.invoke(delegateService, args);
            } catch (InvocationTargetException e) {
                // If the target exception is a declared exception then rethrow as-is
                Throwable targetException = e.getTargetException();
                for (Class<?> declaredException : method.getExceptionTypes()) {
                    // noinspection unchecked
                    Throwables.propagateIfInstanceOf(targetException, (Class<? extends Throwable>) declaredException);
                }
                // If the exception was due to connection issues and not necessarily the target let the caller know.
                // It's possible the connection timed out due to a problem on the target, but from our perspective
                // there's no definitive way of knowing.
                if (targetException instanceof ClientHandlerException) {
                    _errorMeter.mark();
                    throw new PartitionForwardingException("Failed to handle request at endpoint", targetException.getCause());
                }
                throw Throwables.propagate(targetException);
            }
        }
    });

    _proxiedToDelegateServices.put(proxiedService, delegateService);
    return proxiedService;
}
项目:rise    文件:CoreConfigurationNonRestartableTest.java   
@Test
public void testShouldBeScanned() throws Exception {
    CoreConfigurationNonRestartable config = new CoreConfigurationNonRestartable();
    config.scannedPrefixes.add(Reflection.getPackageName(getClass()).replace('.', '/'));
    assertTrue(config.shouldClasspathResourceBeScanned(getClass().getName().replace('.', '/') + ".class"));
    assertFalse(config.shouldClasspathResourceBeScanned("org/eclipse/Test"));
}
项目:auto-parse    文件:CompilationErrorsTest.java   
public void testExceptionBecomesError() throws Exception {
  // Ensure that if the annotation processor code gets an unexpected exception, it is converted
  // into a compiler error rather than being propagated. Otherwise the output can be very
  // confusing to the user who stumbles into a bug that causes an exception, whether in
  // AutoParseProcessor or javac.
  // We inject an exception by rigging fileManager to throw when the processor tries to output
  // the generated class for an otherwise correct @AutoParse class.
  final AtomicBoolean exceptionWasThrown = new AtomicBoolean();
  final String message = "I don't understand the question, and I won't respond to it";
  final StandardJavaFileManager realFileManager = fileManager;
  InvocationHandler errorInjectionHandler = new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      if (method.getName().equals("getJavaFileForOutput")) {
        exceptionWasThrown.set(true);
        throw new UnsupportedOperationException(message);
      } else {
        return method.invoke(realFileManager, args);
      }
    }
  };
  fileManager = Reflection.newProxy(StandardJavaFileManager.class, errorInjectionHandler);
  String testSourceCode =
      "package foo.bar;\n" +
      "import auto.parse.AutoParse;\n" +
      "@AutoParse\n" +
      "public abstract class Empty {\n" +
      "}\n";
  assertCompilationResultIs(
      ImmutableMultimap.of(Diagnostic.Kind.ERROR, Pattern.compile(message, Pattern.LITERAL)),
      ImmutableList.of(testSourceCode));
  assertTrue(exceptionWasThrown.get());
}
项目:guava-libraries    文件:ClassSanityTester.java   
private FactoryMethodReturnValueTester(
    Class<?> declaringClass,
    ImmutableList<Invokable<?, ?>> factories,
    String factoryMethodsDescription) {
  this.declaringClass = declaringClass;
  this.factories = factories;
  this.factoryMethodsDescription = factoryMethodsDescription;
  packagesToTest.add(Reflection.getPackageName(declaringClass));
}