com.google.common.reflect.Reflection Java Examples
The following examples show how to use
com.google.common.reflect.Reflection.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TypedDatabaseSchemaImpl.java From ovsdb with Eclipse Public License 1.0 | 6 votes |
@Override public <T extends TypedBaseTable<?>> T getTypedRowWrapper(final Class<T> klazz, final Row<GenericTableSchema> row) { // Check validity of of the parameter passed to getTypedRowWrapper: // - checks for a valid Database Schema matching the expected Database for a given table // - checks for the presence of the Table in Database Schema. final String dbName = TypedReflections.getTableDatabase(klazz); if (dbName != null && !dbName.equalsIgnoreCase(getName())) { return null; } TyperUtils.checkVersion(getVersion(), TypedReflections.getTableVersionRange(klazz)); TypedRowInvocationHandler handler = handlers.getUnchecked(klazz); if (row != null) { row.setTableSchema(getTableSchema(handler.getTableName())); handler = handler.bindToRow(row); } return Reflection.newProxy(klazz, handler); }
Example #2
Source File: AdWordsServicesWithRateLimiter.java From googleads-java-lib with Apache License 2.0 | 6 votes |
/** * 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); }
Example #3
Source File: TemplateVarsTest.java From auto with Apache License 2.0 | 6 votes |
@Override public void run() { Template template = TemplateVars.parsedTemplateForResource("autovalue.vm"); assertThat(template).isNotNull(); String resourceName = Reflection.getPackageName(getClass()).replace('.', '/') + "/autovalue.vm"; @SuppressWarnings("unchecked") Callable<Set<String>> myLoader = (Callable<Set<String>>) getClass().getClassLoader(); try { Set<String> result = myLoader.call(); assertThat(result).contains(resourceName); assertThat(result).contains("threw"); } catch (Exception e) { throw new AssertionError(e); } }
Example #4
Source File: UniformVisitor.java From closure-stylesheets with Apache License 2.0 | 6 votes |
/** * 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"); } }); }
Example #5
Source File: UniformVisitor.java From closure-stylesheets with Apache License 2.0 | 6 votes |
/** 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"); } }); }
Example #6
Source File: CompositeParseTreeListener.java From protostuff-compiler with Apache License 2.0 | 6 votes |
/** * 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(); } }); }
Example #7
Source File: StashReader.java From emodb with Apache License 2.0 | 6 votes |
protected static AmazonS3 getS3Client(URI stashRoot, final AWSCredentialsProvider credentialsProvider, final @Nullable ClientConfiguration s3Config) { final String bucket = stashRoot.getHost(); // If the bucket is a well-known Stash bucket then the region for the bucket is known in advance. // Otherwise return a proxy which lazily looks up the bucket on the first call. return StashUtil.getRegionForBucket(bucket) .map(region -> createS3ClientForRegion(region, credentialsProvider, s3Config)) .orElseGet(() -> Reflection.newProxy(AmazonS3.class, new AbstractInvocationHandler() { private AmazonS3 _resolvedClient = null; @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(resolvedClient(), args); } private AmazonS3 resolvedClient() { if (_resolvedClient == null) { String endPoint = determineEndpointForBucket(bucket, credentialsProvider, s3Config, stashRoot.getPath()); _resolvedClient = createS3ClientForEndpoint(endPoint, credentialsProvider, s3Config); } return _resolvedClient; } })); }
Example #8
Source File: OstrichAccessors.java From emodb with Apache License 2.0 | 6 votes |
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()); } }); } }; }
Example #9
Source File: S3RateLimiter.java From emodb with Apache License 2.0 | 6 votes |
public AmazonS3 rateLimit(final AmazonS3 delegate) { return Reflection.newProxy(AmazonS3.class, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { int attempts = 0; _l.maybeIncreaseRateLimit(); while (true) { try { _l.beforeS3Method(); return method.invoke(delegate, args); } catch (InvocationTargetException ite) { Throwable t = ite.getTargetException(); attempts += 1; if (attempts == maxAttempts || !_l.checkException(t, method)) { LOGGER.warn("S3 exception being raised to caller after {} attempts", attempts, t); throw _l.asDeclaredThrowable(t, method); } } } } }); }
Example #10
Source File: ValidatorsTest.java From bundletool with Apache License 2.0 | 6 votes |
@Test public void eachSubValidatorIsRegistered() throws Exception { // Load sub-classes of SubValidator that live within the same package as top-level classes. ImmutableSet<Class<?>> existingSubValidators = ClassPath.from(SubValidator.class.getClassLoader()) .getTopLevelClasses(Reflection.getPackageName(SubValidator.class)) .stream() .map(ClassInfo::load) .filter(clazz -> isConcreteSubValidator(clazz)) .collect(toImmutableSet()); ImmutableSet<Class<?>> registeredSubValidators = ImmutableSet.<Class<?>>builder() .addAll(toClasses(AppBundleValidator.DEFAULT_BUNDLE_FILE_SUB_VALIDATORS)) .addAll(toClasses(AppBundleValidator.DEFAULT_BUNDLE_SUB_VALIDATORS)) .addAll(toClasses(BundleModulesValidator.MODULE_FILE_SUB_VALIDATORS)) .addAll(toClasses(BundleModulesValidator.MODULES_SUB_VALIDATORS)) .build(); assertThat(existingSubValidators).containsExactlyElementsIn(registeredSubValidators); }
Example #11
Source File: SelectorBuilder.java From googleads-java-lib with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public SelectorBuilder() { InvocationHandler invocationHandler = new AdsUtilityInvocationHandler( new SelectorBuilderImpl(), AdWordsInternals.getInstance().getAdsUtilityRegistry()); this.impl = Reflection.newProxy(SelectorBuilderInterface.class, invocationHandler); }
Example #12
Source File: ServiceQuery.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** * Constructs a new service query builder by copying all properties from the passed service * query builder. * * @param builderInterface the service query builder whose properties will be copied to. */ @SuppressWarnings("unchecked") public Builder(BuilderInterface<Page, SortOrder> builderInterface) { checkNotNull(builderInterface, "The service query builder cannot be null."); Builder builder = (Builder) builderInterface; proxiedImpl = new ServiceQueryBuilderImpl(builder.proxiedImpl); InvocationHandler invocationHandler = new AdsUtilityInvocationHandler( proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry()); this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler); }
Example #13
Source File: ServiceQuery.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Constructs a new service query builder. */ @SuppressWarnings("unchecked") public Builder() { proxiedImpl = new ServiceQueryBuilderImpl(this); InvocationHandler invocationHandler = new AdsUtilityInvocationHandler( proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry()); this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler); }
Example #14
Source File: BatchJobHelper.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Constructor for Guice. */ @SuppressWarnings("unchecked") @Inject BatchJobHelper(BatchJobHelperImpl helperImpl, AdsUtilityRegistry adsUtilityRegistry) { InvocationHandler invocationHandler = new AdsUtilityInvocationHandler(helperImpl, adsUtilityRegistry); this.impl = Reflection.newProxy(BatchJobHelperInterface.class, invocationHandler); }
Example #15
Source File: AdHocReportDownloadHelper.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Constructor used by Guice. */ @Inject AdHocReportDownloadHelper( AdHocReportDownloadHelperImpl helperImpl, AdsUtilityRegistry adsUtilityRegistry) { InvocationHandler invocationHandler = new AdsUtilityInvocationHandler(helperImpl, adsUtilityRegistry); this.impl = Reflection.newProxy(AdHocReportDownloadHelperInterface.class, invocationHandler); }
Example #16
Source File: ReportQuery.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** * Constructs a new report query builder by copying all properties from the passed report query * builder. * * @param builderInterface the report query builder whose properties will be copied to. */ public Builder(BuilderInterface builderInterface) { checkNotNull(builderInterface, "The report query builder cannot be null."); Builder builder = (Builder) builderInterface; proxiedImpl = new ReportQueryBuilderImpl(builder.proxiedImpl); InvocationHandler invocationHandler = new AdsUtilityInvocationHandler( proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry()); this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler); }
Example #17
Source File: ReportQuery.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Constructs a new report query builder. */ public Builder() { proxiedImpl = new ReportQueryBuilderImpl(this); InvocationHandler invocationHandler = new AdsUtilityInvocationHandler( proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry()); this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler); }
Example #18
Source File: GeneratedAnnotationsTest.java From auto with Apache License 2.0 | 5 votes |
/** * Run {@link TestProcessor} in a compilation with the given {@code options}, and prevent the * compilation from accessing classes with the qualified names in {@code maskFromClasspath}. */ private String runProcessor(ImmutableList<String> options, String packageToMask) throws IOException { File tempDir = temporaryFolder.newFolder(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(/* diagnostics= */ null, /* locale= */ null, UTF_8); standardFileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(tempDir)); StandardJavaFileManager proxyFileManager = Reflection.newProxy( StandardJavaFileManager.class, new FileManagerInvocationHandler(standardFileManager, packageToMask)); CompilationTask task = compiler.getTask( /* out= */ null, proxyFileManager, /* diagnosticListener= */ null, options, /* classes= */ null, ImmutableList.of( new SimpleJavaFileObject(URI.create("test"), Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return "class Test {}"; } })); task.setProcessors(ImmutableList.of(new TestProcessor())); assertThat(task.call()).isTrue(); return new String(Files.readAllBytes(tempDir.toPath().resolve("G.java")), UTF_8); }
Example #19
Source File: PartitionAwareServiceFactory.java From emodb with Apache License 2.0 | 5 votes |
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; }
Example #20
Source File: BatchJobHelper.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Constructor for Guice. */ @SuppressWarnings("unchecked") @Inject BatchJobHelper(BatchJobHelperImpl helperImpl, AdsUtilityRegistry adsUtilityRegistry) { InvocationHandler invocationHandler = new AdsUtilityInvocationHandler(helperImpl, adsUtilityRegistry); this.impl = Reflection.newProxy(BatchJobHelperInterface.class, invocationHandler); }
Example #21
Source File: DelegatingVisitor.java From closure-stylesheets with Apache License 2.0 | 5 votes |
/** * Creates a {@code DelegatingVisitor} from the given list of visitors. The list must have at * least one element. */ public static CssTreeVisitor from(List<CssTreeVisitor> originalVisitors) { Preconditions.checkArgument(originalVisitors.size() >= 1); if (originalVisitors.size() == 1) { return originalVisitors.get(0); } final ImmutableList<CssTreeVisitor> visitors = ImmutableList.copyOf(originalVisitors); final ImmutableList<CssTreeVisitor> reverseVisitors = visitors.reverse(); return Reflection.newProxy( CssTreeVisitor.class, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Object returnValue = null; Iterable<CssTreeVisitor> visitorsInOrderForMethod; if (method.getName().startsWith("enter")) { visitorsInOrderForMethod = visitors; } else { // assume it's a leave* method visitorsInOrderForMethod = reverseVisitors; } for (CssTreeVisitor visitor : visitorsInOrderForMethod) { returnValue = method.invoke(visitor, args); } return returnValue; } catch (InvocationTargetException e) { throw e.getTargetException(); } } }); }
Example #22
Source File: ProxyFactory.java From TakinRPC with Apache License 2.0 | 5 votes |
/** * * @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; }
Example #23
Source File: ApiCatalogImpl.java From google-ads-java with Apache License 2.0 | 5 votes |
/** @inheritDoc */ @Override public GoogleAdsAllVersions createAllVersionsClient( TransportChannelProvider provider, Credentials credentials) { Preconditions.checkNotNull( provider, "Transport channel provider required to create GoogleAdsAllVersions interface."); Preconditions.checkNotNull( credentials, "Credentials are required to create GoogleAdsAllVersions interface."); return Reflection.newProxy( GoogleAdsAllVersions.class, new GoogleAdsAllVersionsInvocationHandler(provider, credentials)); }
Example #24
Source File: TroublesomeBytecodeMisc.java From glowroot with Apache License 2.0 | 5 votes |
@Override public void execute1() { IsolatedWeavingClassLoader loader = (IsolatedWeavingClassLoader) getClass().getClassLoader(); byte[] bytes = generateTroublesomeBytecode(); Class<?> clazz = loader.weaveAndDefineClass("TroublesomeBytecode", bytes, null); Reflection.initialize(clazz); }
Example #25
Source File: ServiceQuery.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Constructs a new service query builder. */ @SuppressWarnings("unchecked") public Builder() { proxiedImpl = new ServiceQueryBuilderImpl(this); InvocationHandler invocationHandler = new AdsUtilityInvocationHandler( proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry()); this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler); }
Example #26
Source File: ServiceQuery.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** * Constructs a new service query builder by copying all properties from the passed service * query builder. * * @param builderInterface the service query builder whose properties will be copied to. */ @SuppressWarnings("unchecked") public Builder(BuilderInterface<Page, SortOrder> builderInterface) { checkNotNull(builderInterface, "The service query builder cannot be null."); Builder builder = (Builder) builderInterface; proxiedImpl = new ServiceQueryBuilderImpl(builder.proxiedImpl); InvocationHandler invocationHandler = new AdsUtilityInvocationHandler( proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry()); this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler); }
Example #27
Source File: ProductPartitionTree.java From googleads-java-lib with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private ProductPartitionTree(final ProductPartitionTreeImpl impl) { InvocationHandler invocationHandler = new AdsUtilityInvocationHandler( impl, AdWordsInternals.getInstance().getAdsUtilityRegistry()) { @Override public String toString() { return impl.toString(); } }; this.impl = Reflection.newProxy(ProductPartitionTreeInterface.class, invocationHandler); }
Example #28
Source File: AsyncTestRunner.java From j2cl with Apache License 2.0 | 5 votes |
private Object createErrorCallback(PromiseType promiseType) { return Reflection.newProxy( promiseType.errorCallbackType, (proxy, method, args) -> { Throwable t = (Throwable) args[0]; future.setException(t); return t; }); }
Example #29
Source File: FastBuildCompilerFactoryImpl.java From intellij with Apache License 2.0 | 5 votes |
private Javac createCompiler(List<File> javacJars) throws FastBuildException { try { Class<?> javacClass = loadJavacClass( FAST_BUILD_JAVAC_CLASS, ImmutableList.<File>builder() .addAll(javacJars) .add(fastBuildJavacJarSupplier.get()) .build()); Constructor<?> createMethod = javacClass.getConstructor(); Object javacInstance = createMethod.newInstance(); FastBuildJavac javaCompiler = Reflection.newProxy( FastBuildJavac.class, new MatchingMethodInvocationHandler(javacClass, javacInstance)); return (context, javacArgs, files, writer) -> { Stopwatch timer = Stopwatch.createStarted(); Object[] rawOutput = javaCompiler.compile(javacArgs, files); CompilerOutput output = CompilerOutput.decode(rawOutput); processDiagnostics(context, output); boolean result = output.result; Command command = Command.builder() .setExecutable(javacJars.get(0).getPath()) .setArguments(javacArgs) .setExitCode(result ? 0 : 1) .setSubcommandName("javac") .setDuration(timer.elapsed()) .build(); eventLoggerSupplier.get().logCommand(getClass(), command); return result; }; } catch (MalformedURLException | ReflectiveOperationException e) { throw new FastBuildIncrementalCompileException(e); } }
Example #30
Source File: SelectorBuilder.java From googleads-java-lib with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public SelectorBuilder() { InvocationHandler invocationHandler = new AdsUtilityInvocationHandler( new SelectorBuilderImpl(), AdWordsInternals.getInstance().getAdsUtilityRegistry()); this.impl = Reflection.newProxy(SelectorBuilderInterface.class, invocationHandler); }