當前位置: 首頁>>代碼示例>>Java>>正文


Java Reflection類代碼示例

本文整理匯總了Java中com.google.common.reflect.Reflection的典型用法代碼示例。如果您正苦於以下問題:Java Reflection類的具體用法?Java Reflection怎麽用?Java Reflection使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Reflection類屬於com.google.common.reflect包,在下文中一共展示了Reflection類的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: getVisibleMethods

import com.google.common.reflect.Reflection; //導入依賴的package包/類
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();
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:18,代碼來源:NullPointerTester.java

示例3: testNulls

import com.google.common.reflect.Reflection; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:26,代碼來源:ClassSanityTester.java

示例4: 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

示例5: 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

示例6: 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

示例7: 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

示例8: 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

示例9: 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

示例10: 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

示例11: 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

示例12: 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

示例13: 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

示例14: getVisibleMethods

import com.google.common.reflect.Reflection; //導入依賴的package包/類
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();
}
 
開發者ID:sander120786,項目名稱:guava-libraries,代碼行數:18,代碼來源:NullPointerTester.java

示例15: testNulls

import com.google.common.reflect.Reflection; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:google,項目名稱:guava,代碼行數:26,代碼來源:ClassSanityTester.java


注:本文中的com.google.common.reflect.Reflection類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。