org.reflections.util.ClasspathHelper Java Examples
The following examples show how to use
org.reflections.util.ClasspathHelper.
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: DataScopeSqlConfigService.java From smart-admin with MIT License | 7 votes |
/** * 刷新 所有添加数据范围注解的接口方法配置<class.method,DataScopeSqlConfigDTO></> * * @return */ private Map<String, DataScopeSqlConfigDTO> refreshDataScopeMethodMap() { Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(scanPackage)).setScanners(new MethodAnnotationsScanner())); Set<Method> methods = reflections.getMethodsAnnotatedWith(DataScope.class); for (Method method : methods) { DataScope dataScopeAnnotation = method.getAnnotation(DataScope.class); if (dataScopeAnnotation != null) { DataScopeSqlConfigDTO configDTO = new DataScopeSqlConfigDTO(); configDTO.setDataScopeType(dataScopeAnnotation.dataScopeType().getType()); configDTO.setJoinSql(dataScopeAnnotation.joinSql()); configDTO.setWhereIndex(dataScopeAnnotation.whereIndex()); dataScopeMethodMap.put(method.getDeclaringClass().getSimpleName() + "." + method.getName(), configDTO); } } return dataScopeMethodMap; }
Example #2
Source File: MessagesScanner.java From elasticactors with Apache License 2.0 | 6 votes |
@PostConstruct public void init() { String[] basePackages = ScannerHelper.findBasePackagesOnClasspath(applicationContext.getClassLoader()); ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); for (String basePackage : basePackages) { configurationBuilder.addUrls(ClasspathHelper.forPackage(basePackage)); } Reflections reflections = new Reflections(configurationBuilder); Set<Class<?>> messageClasses = reflections.getTypesAnnotatedWith(Message.class); for (Class<?> messageClass : messageClasses) { Message messageAnnotation = messageClass.getAnnotation(Message.class); // get the serialization framework SerializationFramework framework = applicationContext.getBean(messageAnnotation.serializationFramework()); framework.register(messageClass); } }
Example #3
Source File: CasLoggerContextInitializer.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
/** * Prepares the logger context. Locates the context and * sets the configuration file. * @return the logger context */ private ServletContextListener prepareAndgetContextListener() { try { if (StringUtils.isNotBlank(this.loggerContextPackageName)) { final Collection<URL> set = ClasspathHelper.forPackage(this.loggerContextPackageName); final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner())); final Set<Class<? extends ServletContextListener>> subTypesOf = reflections.getSubTypesOf(ServletContextListener.class); final ServletContextListener loggingContext = subTypesOf.iterator().next().newInstance(); this.context.setInitParameter(this.logConfigurationField, this.logConfigurationFile.getURI().toString()); return loggingContext; } return null; } catch (final Exception e) { throw new RuntimeException(e); } }
Example #4
Source File: GuiceBundle.java From robe with GNU Lesser General Public License v3.0 | 6 votes |
/** * Creates a {@link org.reflections.Reflections} with the given packages (configuration) * * @param scanPackages */ private void createReflections(String[] scanPackages) { if (scanPackages.length < 1) { LOGGER.warn("No package defined in configuration (scanPackages)!"); return; } ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); FilterBuilder filterBuilder = new FilterBuilder(); for (String packageName : scanPackages) { configurationBuilder.addUrls(ClasspathHelper.forPackage(packageName)); filterBuilder.include(FilterBuilder.prefix(packageName)); } configurationBuilder.filterInputsBy(filterBuilder).setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()); this.reflections = new Reflections(configurationBuilder); }
Example #5
Source File: ActivitySerDeTest.java From streams with Apache License 2.0 | 6 votes |
/** * Tests that defined activity verbs have an example which can be loaded into * Activity beans and into verb-specific beans. * @throws Exception Exception */ @Test public void testVerbSerDe() throws Exception { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json")) .setScanners(new SubTypesScanner())); Set<Class<? extends Activity>> verbs = reflections.getSubTypesOf(Activity.class); for ( Class verbClass : verbs) { LOGGER.info("Verb: " + verbClass.getSimpleName() ); Activity activity = (Activity) verbClass.newInstance(); String verbName = activity.getVerb(); String testfile = verbName.toLowerCase() + ".json"; LOGGER.info("Serializing: activities/" + testfile ); Path testActivityPath = Paths.get("target/dependency/activitystreams-testdata/" + testfile); assert (testActivityPath.toFile().exists()); FileInputStream testActivityFileStream = new FileInputStream(testActivityPath.toFile()); assert (testActivityFileStream != null); activity = MAPPER.convertValue(MAPPER.readValue(testActivityFileStream, verbClass), Activity.class); String activityString = MAPPER.writeValueAsString(activity); LOGGER.info("Deserialized: " + activityString ); assert ( !activityString.contains("null") ); assert ( !activityString.contains("[]") ); } }
Example #6
Source File: StreamsJacksonModule.java From streams with Apache License 2.0 | 6 votes |
public StreamsJacksonModule() { super(); Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("org.apache.streams.jackson")) .setScanners(new SubTypesScanner())); Set<Class<? extends StreamsDateTimeFormat>> dateTimeFormatClasses = reflections.getSubTypesOf(StreamsDateTimeFormat.class); List<String> dateTimeFormats = new ArrayList<>(); for (Class dateTimeFormatClass : dateTimeFormatClasses) { try { dateTimeFormats.add(((StreamsDateTimeFormat) (dateTimeFormatClass.newInstance())).getFormat()); } catch (Exception ex) { LOGGER.warn("Exception getting format from " + dateTimeFormatClass); } } addSerializer(DateTime.class, new StreamsDateTimeSerializer(DateTime.class)); addDeserializer(DateTime.class, new StreamsDateTimeDeserializer(DateTime.class, dateTimeFormats)); addSerializer(Period.class, new StreamsPeriodSerializer(Period.class)); addDeserializer(Period.class, new StreamsPeriodDeserializer(Period.class)); }
Example #7
Source File: ElasticsearchParentChildUpdaterIT.java From streams with Apache License 2.0 | 6 votes |
@BeforeClass public void prepareTestParentChildPersistUpdater() throws Exception { testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration( "ElasticsearchParentChildUpdaterIT"); testClient = ElasticsearchClientManager.getInstance(testConfiguration).client(); ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest(); ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet(); assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED); IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex()); IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet(); assertTrue(indicesExistsResponse.isExists()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json")) .setScanners(new SubTypesScanner())); objectTypes = reflections.getSubTypesOf(ActivityObject.class); Path testdataDir = Paths.get("target/dependency/activitystreams-testdata"); files = Files.list(testdataDir).collect(Collectors.toList()); }
Example #8
Source File: SchemaGeneratorTest.java From kafka-connect-twitter with Apache License 2.0 | 6 votes |
@Test public void tweetEntities() { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forJavaClassPath()) .forPackages(TweetEntity.class.getPackage().getName()) ); List<Class<?>> allClasses = new ArrayList<>(); List<Class<? extends TweetEntity>> classes = list(reflections, TweetEntity.class); allClasses.add(MediaEntity.Variant.class); allClasses.add(MediaEntity.Size.class); allClasses.addAll(classes); for (Class<?> cls : allClasses) { StringBuilder builder = new StringBuilder(); processClass(cls, builder); System.out.println(builder); } }
Example #9
Source File: ClassloaderScanner.java From yawp with MIT License | 6 votes |
private Reflections buildReflections(String packages) { String[] packagesArray = packages.replaceAll(" ", "").split(","); FilterBuilder filter = new FilterBuilder(); Set<URL> urls = new HashSet(); for (String packageStr : packagesArray) { urls.addAll(ClasspathHelper.forPackage(packageStr)); filter.include(FilterBuilder.prefix(packageStr)); } return new Reflections(new ConfigurationBuilder() .addUrls(urls) .filterInputsBy(filter) .setScanners(new TypeAnnotationsScanner(), new SubTypesScanner())); }
Example #10
Source File: ReflectionsServiceDiscovery.java From katharsis-framework with Apache License 2.0 | 6 votes |
public ReflectionsServiceDiscovery(String resourceSearchPackages, JsonServiceLocator locator) { this.locator = locator; ConfigurationBuilder builder = new ConfigurationBuilder(); PreconditionUtil.assertNotNull("no resourceSearchPackage configured", resourceSearchPackages); FilterBuilder filter = new FilterBuilder(); for (String resourceSearchPackage : resourceSearchPackages.split(",")) { builder = builder.addUrls(ClasspathHelper.forPackage(resourceSearchPackage)); filter.includePackage(resourceSearchPackage); } filter.includePackage(Repository.class.getPackage().getName()); filter.includePackage(ResourceRepository.class.getPackage().getName()); builder = builder.filterInputsBy(filter); builder = builder.addUrls(ClasspathHelper.forClass(Repository.class)); builder = builder.addUrls(ClasspathHelper.forClass(ResourceRepository.class)); builder = builder.addUrls(ClasspathHelper.forClass(ResourceRepositoryV2.class)); builder = builder.setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner()); reflections = new Reflections(builder); }
Example #11
Source File: AnnotationLoader.java From livingdoc-core with GNU General Public License v3.0 | 6 votes |
public void addLoader(ClassLoader loader) { if (builder == null) { this.builder = new ConfigurationBuilder(); builder.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()); } builder.addClassLoader(loader); builder.addUrls(ClasspathHelper.forClassLoader(loader)); if(loader instanceof JoinClassLoader) { // When the object "reflections" is created in the method scanClassPath(), are scanned the URLs so // it is necessary to add the URLs from the enclosing class loader in the JoinClassLoader that it // contains the fixture classpath (see org.reflections.Reflections.scan()). builder.addUrls(ClasspathHelper.forClassLoader(((JoinClassLoader) loader).getEnclosingClassLoader())); } scanClassPath(builder); }
Example #12
Source File: RoleClassLoader.java From anno4j with Apache License 2.0 | 6 votes |
private void scanConceptsWithReflections() throws ObjectStoreConfigException { logger.debug("Search for concepts with reflections"); Set<URL> classpath = new HashSet<>(); classpath.addAll(ClasspathHelper.forClassLoader()); classpath.addAll(ClasspathHelper.forJavaClassPath()); classpath.addAll(ClasspathHelper.forManifest()); classpath.addAll(ClasspathHelper.forPackage("")); Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(classpath) .useParallelExecutor() .filterInputsBy(FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun")) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Iri.class, true); logger.debug("Search for concepts with reflections resulted in " + annotated.size() + " classes"); for (Class clazz : annotated) { logger.debug("Found concept class: " + clazz.getCanonicalName()); roleMapper.addConcept(clazz); } }
Example #13
Source File: ProxyCompileTool.java From anno4j with Apache License 2.0 | 6 votes |
/** * Creates an Anno4j instance that can use the concepts contained in the given JAR file. * @param ontologyJar A JAR file containing concepts. * @param classLoader The class loader to use. * @param persistSchemaAnnotations Whether schema annotations should be scanned. * @return Returns an Anno4j instance. * @throws Exception Thrown on error. */ private static Anno4j getAnno4jWithClassLoader(File ontologyJar, ClassLoader classLoader, boolean persistSchemaAnnotations) throws Exception { Set<URL> clazzes = new HashSet<>(); clazzes.addAll(ClasspathHelper.forManifest(ontologyJar.toURI().toURL())); Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), new IDGeneratorAnno4jURN(), null, persistSchemaAnnotations, clazzes); // Register concepts found in JAR: RoleMapper mapper = anno4j.getObjectRepository().getConnection().getObjectFactory().getResolver().getRoleMapper(); for (final String className : getClassNamesInJar(ontologyJar)) { Class<?> clazz = classLoader.loadClass(className); if(clazz.getAnnotation(Iri.class) != null) { mapper.addConcept(clazz); } } return anno4j; }
Example #14
Source File: ElasticsearchParentChildWriterIT.java From streams with Apache License 2.0 | 5 votes |
@BeforeClass public void prepareTestParentChildPersistWriter() throws Exception { testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration("ElasticsearchParentChildWriterIT"); testClient = ElasticsearchClientManager.getInstance(testConfiguration).client(); ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest(); ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet(); assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED); IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex()); IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet(); if (indicesExistsResponse.isExists()) { DeleteIndexRequest deleteIndexRequest = Requests.deleteIndexRequest(testConfiguration.getIndex()); DeleteIndexResponse deleteIndexResponse = testClient.admin().indices().delete(deleteIndexRequest).actionGet(); assertTrue(deleteIndexResponse.isAcknowledged()); } PutIndexTemplateRequestBuilder putTemplateRequestBuilder = testClient.admin().indices().preparePutTemplate("mappings"); URL templateURL = ElasticsearchParentChildWriterIT.class.getResource("/ActivityChildObjectParent.json"); ObjectNode template = MAPPER.readValue(templateURL, ObjectNode.class); String templateSource = MAPPER.writeValueAsString(template); putTemplateRequestBuilder.setSource(templateSource); testClient.admin().indices().putTemplate(putTemplateRequestBuilder.request()).actionGet(); Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json")) .setScanners(new SubTypesScanner())); objectTypes = reflections.getSubTypesOf(ActivityObject.class); Path testdataDir = Paths.get("target/dependency/activitystreams-testdata"); files = Files.list(testdataDir).collect(Collectors.toList()); assert( files.size() > 0); }
Example #15
Source File: ClasspathScanner.java From valdr-bean-validation with MIT License | 5 votes |
private Collection<URL> buildClassLoaderUrls() { Collection<URL> urls = Sets.newHashSet(); for (String packageName : options.getModelPackages()) { if (StringUtils.isNotEmpty(packageName)) { urls.addAll(ClasspathHelper.forPackage(packageName)); } } return urls; }
Example #16
Source File: NativeImageHelper.java From arangodb-java-driver with Apache License 2.0 | 5 votes |
private static void generateReflectConfig() throws JsonProcessingException { System.out.println("---------------------------"); System.out.println("--- reflect-config.json ---"); System.out.println("---------------------------"); List<String> packages = Arrays.asList("com.arangodb.entity", "com.arangodb.model"); ObjectMapper mapper = new ObjectMapper(); ArrayNode rootNode = mapper.createArrayNode(); ObjectNode noArgConstructor = mapper.createObjectNode(); noArgConstructor.put("name", "<init>"); noArgConstructor.set("parameterTypes", mapper.createArrayNode()); ArrayNode methods = mapper.createArrayNode(); methods.add(noArgConstructor); packages.stream() .flatMap(p -> { final ConfigurationBuilder config = new ConfigurationBuilder() .setScanners(new ResourcesScanner(), new SubTypesScanner(false)) .setUrls(ClasspathHelper.forPackage(p)) .filterInputsBy(new FilterBuilder().includePackage(p)); return new Reflections(config).getSubTypesOf(Object.class).stream(); }) .map(Class::getName) .map(className -> { ObjectNode entry = mapper.createObjectNode(); entry.put("name", className); entry.put("allDeclaredFields", true); entry.set("methods", methods); return entry; }) .forEach(rootNode::add); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode); System.out.println(jsonString); }
Example #17
Source File: AbstractAssertTestsClass.java From deeplearning4j with Apache License 2.0 | 5 votes |
@Test public void checkTestClasses(){ Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(getPackageName())) .setScanners(new MethodAnnotationsScanner())); Set<Method> methods = reflections.getMethodsAnnotatedWith(Test.class); Set<Class<?>> s = new HashSet<>(); for(Method m : methods){ s.add(m.getDeclaringClass()); } List<Class<?>> l = new ArrayList<>(s); Collections.sort(l, new Comparator<Class<?>>() { @Override public int compare(Class<?> aClass, Class<?> t1) { return aClass.getName().compareTo(t1.getName()); } }); int count = 0; for(Class<?> c : l){ if(!getBaseClass().isAssignableFrom(c) && !getExclusions().contains(c)){ log.error("Test {} does not extend {} (directly or indirectly). All tests must extend this class for proper memory tracking and timeouts", c, getBaseClass()); count++; } } assertEquals("Number of tests not extending BaseND4JTest", 0, count); }
Example #18
Source File: CheckForbiddenMethodsUsage.java From flink with Apache License 2.0 | 5 votes |
@Test public void testNoDefaultEncoding() throws Exception { final Reflections reflections = new Reflections(new ConfigurationBuilder() .useParallelExecutor(Runtime.getRuntime().availableProcessors()) .addUrls(ClasspathHelper.forPackage("org.apache.flink")) .addScanners(new MemberUsageScanner())); for (ForbiddenCall forbiddenCall : forbiddenCalls) { final Set<Member> methodUsages = forbiddenCall.getUsages(reflections); methodUsages.removeAll(forbiddenCall.getExclusions()); assertEquals("Unexpected calls: " + methodUsages, 0, methodUsages.size()); } }
Example #19
Source File: ClasspathConfigSource.java From incubator-gobblin with Apache License 2.0 | 5 votes |
/** * Scan the classpath for {@link #classpathRootName} and return all resources under it. * {@inheritDoc} * @see org.apache.gobblin.config.store.deploy.DeployableConfigSource#getDeployableConfigPaths() */ private Set<String> getDeployableConfigPaths() { ConfigurationBuilder cb = new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader()).setScanners(new ResourcesScanner()) .filterInputsBy(new FilterBuilder().include(String.format(".*%s.*", this.classpathRootName))); Reflections reflections = new Reflections(cb); Pattern pattern = Pattern.compile(".*"); return reflections.getResources(pattern); }
Example #20
Source File: Manager.java From hbase-tools with Apache License 2.0 | 5 votes |
private static Reflections createReflections() { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); return new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader( classLoadersList.toArray(new ClassLoader[classLoadersList.size()])))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command")))); }
Example #21
Source File: TestRunner.java From at.info-knowledge-base with MIT License | 5 votes |
private static Set<Method> getMethodsForTag(String tag) { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("info.at.tagging")) .setScanners(new MethodAnnotationsScanner())); Set<Method> testMethods = new HashSet<>(); Set<Method> allMethods = reflections.getMethodsAnnotatedWith(Tag.class); for (Method klass : allMethods) { if (Arrays.asList(klass.getAnnotation(Tag.class).value()).contains(tag)) { testMethods.add(klass); } } return testMethods; }
Example #22
Source File: Manager.java From hbase-tools with Apache License 2.0 | 5 votes |
private static Reflections createReflections() { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); return new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader( classLoadersList.toArray(new ClassLoader[classLoadersList.size()])))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command")))); }
Example #23
Source File: Manager.java From hbase-tools with Apache License 2.0 | 5 votes |
private static Reflections createReflections() { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); return new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader( classLoadersList.toArray(new ClassLoader[classLoadersList.size()])))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command")))); }
Example #24
Source File: Manager.java From hbase-tools with Apache License 2.0 | 5 votes |
private static Reflections createReflections() { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); return new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader( classLoadersList.toArray(new ClassLoader[classLoadersList.size()])))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command")))); }
Example #25
Source File: FunctionalTypeTest.java From FreeBuilder with Apache License 2.0 | 5 votes |
private UnaryOperatorFinder() { Reflections reflections = new Reflections( "java.util.function", ClasspathHelper.forClass(UnaryOperator.class)); unaryOperatorClasses = reflections .getTypesAnnotatedWith(FunctionalInterface.class) .stream() .flatMap(cls -> Arrays.stream(cls.getMethods())) .filter(method -> Modifier.isAbstract(method.getModifiers())) .filter(method -> method.getParameterTypes().length == 1) .filter(method -> method.getGenericParameterTypes()[0] .equals(method.getGenericReturnType())) .collect(toMap( method -> TypeToken.of(method.getGenericReturnType()), Method::getDeclaringClass)); }
Example #26
Source File: ReflectionsApp.java From tutorials with MIT License | 5 votes |
public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() { Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections")) .setScanners(new SubTypesScanner())); Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class); return scannersSet; }
Example #27
Source File: ModelInfoLookup.java From archie with Apache License 2.0 | 5 votes |
/** * Add all subtypes of the given class * @param baseClass */ protected void addSubtypesOf(Class baseClass) { Reflections reflections = new Reflections(ClasspathHelper.forClass(baseClass), new SubTypesScanner(false)); Set<Class<?>> classes = reflections.getSubTypesOf(baseClass); System.out.println("type names size: " + classes.size()); classes.forEach(this::addClass); }
Example #28
Source File: TypesafeConfigModule.java From typesafeconfig-guice with Apache License 2.0 | 5 votes |
public static Reflections createPackageScanningReflections(String packageNamePrefix){ ConfigurationBuilder configBuilder = new ConfigurationBuilder() .filterInputsBy(new FilterBuilder().includePackage(packageNamePrefix)) .setUrls(ClasspathHelper.forPackage(packageNamePrefix)) .setScanners( new TypeAnnotationsScanner(), new MethodParameterScanner(), new MethodAnnotationsScanner(), new FieldAnnotationsScanner() ); return new Reflections(configBuilder); }
Example #29
Source File: PluggableMessageHandlersScanner.java From elasticactors with Apache License 2.0 | 5 votes |
@Override @PostConstruct public void init() { String[] basePackages = ScannerHelper.findBasePackagesOnClasspath(applicationContext.getClassLoader()); ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); for (String basePackage : basePackages) { configurationBuilder.addUrls(ClasspathHelper.forPackage(basePackage)); } Reflections reflections = new Reflections(configurationBuilder); Set<Class<?>> handlerClasses = reflections.getTypesAnnotatedWith(PluggableMessageHandlers.class); for (Class<?> handlerClass : handlerClasses) { PluggableMessageHandlers handlerAnnotation = handlerClass.getAnnotation(PluggableMessageHandlers.class); registry.put(handlerAnnotation.value(),handlerClass); } Set<Class<? extends ActorLifecycleListener>> listenerClasses = reflections.getSubTypesOf(ActorLifecycleListener.class); for (Class<? extends ActorLifecycleListener> listenerClass : listenerClasses) { try { ActorLifecycleListener lifeCycleListener = listenerClass.newInstance(); // ensure that the lifeCycle listener handles the correct state class lifecycleListeners.put(lifeCycleListener.getActorClass(), lifeCycleListener); } catch(Exception e) { logger.error("Exception while instantiating ActorLifeCycleListener",e); } } }
Example #30
Source File: BrooklynRestApiTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
private void forceUseOfDefaultCatalogWithJavaClassPath() { // don't use any catalog.xml which is set ((BrooklynProperties)manager.getConfig()).put(BrooklynServerConfig.BROOKLYN_CATALOG_URL, SCANNING_CATALOG_BOM_URL); // sets URLs for a surefire ((LocalManagementContext)manager).setBaseClassPathForScanning(ClasspathHelper.forJavaClassPath()); // this also works // ((LocalManagementContext)manager).setBaseClassPathForScanning(ClasspathHelper.forPackage("brooklyn")); // but this (near-default behaviour) does not // ((LocalManagementContext)manager).setBaseClassLoader(getClass().getClassLoader()); }