类org.springframework.core.type.filter.AssignableTypeFilter源码实例Demo

下面列出了怎么用org.springframework.core.type.filter.AssignableTypeFilter的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: gemini   文件: ErrorService.java
@Override
public void afterPropertiesSet() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(GeminiException.class));
    Set<BeanDefinition> components = provider.findCandidateComponents("it.at7.gemini");
    for (BeanDefinition component : components) {
        Class<?> gemException = Class.forName(component.getBeanClassName());
        Class<?>[] innerClasses = gemException.getDeclaredClasses();
        for (Class<?> innerClass : innerClasses) {
            String simpleName = innerClass.getSimpleName();
            if (simpleName.equals("Code")) {
                Enum[] enumConstants = (Enum[]) innerClass.getEnumConstants();
                register(enumConstants);
            }
        }
    }
}
 
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaults() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
	scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	int beanCount = scanner.scan(BASE_PACKAGE);

	assertEquals(11, beanCount);
	assertFalse(context.containsBean("fooServiceImpl"));
	assertTrue(context.containsBean("serviceInvocationCounter"));
	assertTrue(context.containsBean("stubFooDao"));
	assertTrue(context.containsBean("myNamedComponent"));
	assertTrue(context.containsBean("myNamedDao"));
	assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
 
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaultsWithoutPostProcessors() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
	scanner.setIncludeAnnotationConfig(false);
	scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	int beanCount = scanner.scan(BASE_PACKAGE);

	assertEquals(6, beanCount);
	assertFalse(context.containsBean("fooServiceImpl"));
	assertTrue(context.containsBean("serviceInvocationCounter"));
	assertTrue(context.containsBean("stubFooDao"));
	assertTrue(context.containsBean("myNamedComponent"));
	assertTrue(context.containsBean("myNamedDao"));
	assertFalse(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertFalse(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
 
@Test
public void testMultipleCustomExcludeFiltersAndDefaults() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
	scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class));
	int beanCount = scanner.scan(BASE_PACKAGE);

	assertEquals(10, beanCount);
	assertFalse(context.containsBean("fooServiceImpl"));
	assertFalse(context.containsBean("serviceInvocationCounter"));
	assertTrue(context.containsBean("stubFooDao"));
	assertTrue(context.containsBean("myNamedComponent"));
	assertTrue(context.containsBean("myNamedDao"));
	assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
 
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaults() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
	scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	int beanCount = scanner.scan(BASE_PACKAGE);

	assertEquals(11, beanCount);
	assertFalse(context.containsBean("fooServiceImpl"));
	assertTrue(context.containsBean("serviceInvocationCounter"));
	assertTrue(context.containsBean("stubFooDao"));
	assertTrue(context.containsBean("myNamedComponent"));
	assertTrue(context.containsBean("myNamedDao"));
	assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
 
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaultsWithoutPostProcessors() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
	scanner.setIncludeAnnotationConfig(false);
	scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	int beanCount = scanner.scan(BASE_PACKAGE);

	assertEquals(6, beanCount);
	assertFalse(context.containsBean("fooServiceImpl"));
	assertTrue(context.containsBean("serviceInvocationCounter"));
	assertTrue(context.containsBean("stubFooDao"));
	assertTrue(context.containsBean("myNamedComponent"));
	assertTrue(context.containsBean("myNamedDao"));
	assertFalse(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertFalse(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
 
@Test
public void testMultipleCustomExcludeFiltersAndDefaults() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
	scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class));
	int beanCount = scanner.scan(BASE_PACKAGE);

	assertEquals(10, beanCount);
	assertFalse(context.containsBean("fooServiceImpl"));
	assertFalse(context.containsBean("serviceInvocationCounter"));
	assertTrue(context.containsBean("stubFooDao"));
	assertTrue(context.containsBean("myNamedComponent"));
	assertTrue(context.containsBean("myNamedDao"));
	assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
 
源代码8 项目: ESarch   文件: CommandController.java
@PostConstruct
private void initializeCommandApi() {
    logger.info("Initialising the command API list.");

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    BASE_COMMAND_CLASS.forEach(superCmdClazz -> provider.addIncludeFilter(new AssignableTypeFilter(superCmdClazz)));

    List<String> commandClassNames = provider.findCandidateComponents(CORE_API_PACKAGE)
                                             .stream()
                                             .map(BeanDefinition::getBeanClassName)
                                             .collect(Collectors.toList());

    simpleToFullClassName = commandClassNames.stream().collect(Collectors.toMap(
            this::simpleCommandClassName, commandClassName -> commandClassName
    ));

    commandApi = commandClassNames.stream().collect(Collectors.toMap(
            this::simpleCommandClassName, this::commandJsonSchema
    ));

    logger.info("{} commands available.", commandApi.size());
}
 
@Test
public void testCompileExtendedServices() throws Exception
{
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(Extensible.class));

    Set<BeanDefinition> components = provider.findCandidateComponents("org/alfresco/*");
    Set<Class<? extends Extensible>> extensibles = new HashSet<>();
    for (BeanDefinition component : components)
    {
        @SuppressWarnings("unchecked")
        Class<? extends Extensible> extensibleClass = (Class<? extends Extensible>) Class.forName(component
                    .getBeanClassName());
        extensibles.add(extensibleClass);

    }
    compile(extensibles);
}
 
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaults() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
	scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	int beanCount = scanner.scan(BASE_PACKAGE);
	assertEquals(11, beanCount);
	assertFalse(context.containsBean("fooServiceImpl"));
	assertTrue(context.containsBean("serviceInvocationCounter"));
	assertTrue(context.containsBean("stubFooDao"));
	assertTrue(context.containsBean("myNamedComponent"));
	assertTrue(context.containsBean("myNamedDao"));
	assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
 
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaultsWithoutPostProcessors() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
	scanner.setIncludeAnnotationConfig(false);
	scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	int beanCount = scanner.scan(BASE_PACKAGE);
	assertEquals(5, beanCount);
	assertFalse(context.containsBean("fooServiceImpl"));
	assertTrue(context.containsBean("serviceInvocationCounter"));
	assertTrue(context.containsBean("stubFooDao"));
	assertTrue(context.containsBean("myNamedComponent"));
	assertTrue(context.containsBean("myNamedDao"));
	assertFalse(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertFalse(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertFalse(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
 
@Test
public void testMultipleCustomExcludeFiltersAndDefaults() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
	scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class));
	int beanCount = scanner.scan(BASE_PACKAGE);
	assertEquals(10, beanCount);
	assertFalse(context.containsBean("fooServiceImpl"));
	assertFalse(context.containsBean("serviceInvocationCounter"));
	assertTrue(context.containsBean("stubFooDao"));
	assertTrue(context.containsBean("myNamedComponent"));
	assertTrue(context.containsBean("myNamedDao"));
	assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
	assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
 
@Override
public Set<Class<?>> getSubClasses(Class<?> clazz, String basePackage) {
  ClassPathScanningCandidateComponentProvider provider =
      new ClassPathScanningCandidateComponentProvider(false);
  provider.addIncludeFilter(new AssignableTypeFilter(clazz));

  Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);

  return components
      .stream()
      .map(
          component -> {
            try {
              return Class.forName(component.getBeanClassName());
            } catch (ClassNotFoundException e) {
              throw new IllegalStateException(
                  String.format("Could not load child class '%s'.", component.getBeanClassName()),
                  e);
            }
          })
      .collect(Collectors.toSet());
}
 
源代码14 项目: cqrs-es-kafka   文件: CommandHandlerUtils.java
public static Map<String, CommandHandler> buildCommandHandlersRegistry(final String basePackage,
                                                                       final ApplicationContext context) {

    final Map<String, CommandHandler> registry = new HashMap<>();
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    scanner.addIncludeFilter(new AssignableTypeFilter(CommandHandler.class));

    CommandHandler currentHandler = null;

    for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) {
        currentHandler = (CommandHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()),
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        registry.put(currentHandler.getInterest(), currentHandler);
    }

    return registry;
}
 
源代码15 项目: cqrs-es-kafka   文件: EventHandlerUtils.java
public static Map<String, EventHandler> buildEventHandlersRegistry(final String basePackage,
                                                                   final ApplicationContext context) {

    final Map<String, EventHandler> registry = new HashMap<>();
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    scanner.addIncludeFilter(new AssignableTypeFilter(EventHandler.class));

    EventHandler currentHandler = null;

    for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) {
        currentHandler = (EventHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()),
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        registry.put(currentHandler.getInterest(), currentHandler);
    }

    return registry;
}
 
源代码16 项目: moserp   文件: RestConfiguration.java
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(IdentifiableEntity.class));
    Set<BeanDefinition> components = provider.findCandidateComponents(this.getClass().getPackage().getName());
    List<Class<?>> classes = new ArrayList<>();

    components.forEach(component -> {
        try {
            classes.add(Class.forName(component.getBeanClassName()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

    config.exposeIdsFor(classes.toArray(new Class[classes.size()]));
}
 
源代码17 项目: zstack   文件: ConfigurationManagerImpl.java
private void generateApiMessageGroovyClass(StringBuilder sb, List<String> basePkgs) {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(APIMessage.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(APIReply.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(APIEvent.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
    for (String pkg : basePkgs) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
            try {
                Class<?> clazz = Class.forName(bd.getBeanClassName());
                //classToApiMessageGroovyClass(sb, clazz);
                classToApiMessageGroovyInformation(sb, clazz);
            } catch (ClassNotFoundException e) {
                logger.warn(String.format("Unable to generate groovy class for %s", bd.getBeanClassName()), e);
            }
        }
    }
}
 
源代码18 项目: zstack   文件: Deployer.java
private void scanDeployer() {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(AbstractDeployer.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(org.springframework.stereotype.Component.class));
    for (BeanDefinition bd : scanner.findCandidateComponents("org.zstack.test")) {
        try {
            Class<?> clazz = Class.forName(bd.getBeanClassName());
            AbstractDeployer d = (AbstractDeployer) clazz.newInstance();
            deployers.put(d.getSupportedDeployerClassType(), d);
            logger.debug(String.format("Scanned a deployer[%s] supporting %s", d.getClass().getName(), d.getSupportedDeployerClassType()));
        } catch (Exception e) {
            logger.warn(String.format("unable to create deployer[%s], it's probably there are some beans requried by deployer is not loaded, skip it. error message:\n%s", bd.getBeanClassName(), e.getMessage()));
        }

    }
}
 
源代码19 项目: zstack   文件: RESTApiFacadeImpl.java
void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Set<APIEvent> boundEvents = new HashSet<APIEvent>(100);
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.resetFilters(false);
    scanner.addIncludeFilter(new AssignableTypeFilter(APIEvent.class));
    for (String pkg : getBasePkgNames()) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
            Class<?> clazz = Class.forName(bd.getBeanClassName());
            if (clazz == APIEvent.class) {
                continue;
            }
            APIEvent evt = (APIEvent) clazz.newInstance();
            boundEvents.add(evt);
        }
    }

    for (APIEvent e : boundEvents) {
        bus.subscribeEvent(this, e);
    }
}
 
private Class<?>[] findSubTypes() {
	List<Class<?>> types = new ArrayList<>();
	if (this.packagesToScan != null) {
		for (String pkg : this.packagesToScan) {
			ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
					false);
			provider.addIncludeFilter(
					new AssignableTypeFilter(RemoteApplicationEvent.class));

			Set<BeanDefinition> components = provider.findCandidateComponents(pkg);
			for (BeanDefinition component : components) {
				try {
					types.add(Class.forName(component.getBeanClassName()));
				}
				catch (ClassNotFoundException e) {
					throw new IllegalStateException(
							"Failed to scan classpath for remote event classes", e);
				}
			}
		}
	}
	if (log.isDebugEnabled()) {
		log.debug("Found sub types: " + types);
	}
	return types.toArray(new Class<?>[0]);
}
 
源代码21 项目: kfs   文件: WebServicesImplTest.java
public void testWebServices() throws Exception {
    

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(KfsKcSoapService.class));
    Set<BeanDefinition> components = provider.findCandidateComponents(TEST_BASE_PACKAGE);
    for (BeanDefinition component : components) {
        String className = component.getBeanClassName();
        Class<KfsKcSoapService> kfsServiceClass = (Class<KfsKcSoapService>) Class.forName(className);
        try {
            KfsKcSoapService kfsServiceInst = kfsServiceClass.newInstance();
            URL myWsdl = kfsServiceInst.getWsdl();
            assertTrue(isValidfetchXML(myWsdl));
        }
        catch (Exception ex) {
            fail(ex.getMessage());
        }
    }
}
 
源代码22 项目: rice   文件: QueryByCriteriaJaxbTest.java
/**
 * Search the classes in the PREDICATE_BASE_PACKAGE and build a list of all simple (non-composite) Predicate classes
 * @return a list of simple Predicate classes
 * @throws ClassNotFoundException
 */
private ArrayList<Class<?>> discoverSimplePredicateClasses() throws ClassNotFoundException {
    ArrayList<Class<?>> discoveredPredicateClasses = new ArrayList<Class<?>>();

    // This technique was copped from:
    // http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(Predicate.class));

    // scan in org.example.package
    Set<BeanDefinition> components = provider.findCandidateComponents(PREDICATE_BASE_PACKAGE);
    for (BeanDefinition component : components)
    {
        Class cls = Class.forName(component.getBeanClassName());
        if (!cls.isMemberClass()                             // filter out inner class predicates from test packages
            && Predicate.class.isAssignableFrom(cls)         // filter out any non-predicate classes
            && !CompositePredicate.class.isAssignableFrom(cls)) // filter out 'and' and 'or' predicates
        {
            discoveredPredicateClasses.add(cls);
            // use class cls found
            LOG.debug("discovered " + cls.toString());
        }
    }
    return discoveredPredicateClasses;
}
 
@Test
public void failIfNewTypeOfMaterialIsNotAddedInTheAboveTest() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(MaterialConfig.class));
    Set<BeanDefinition> candidateComponents = provider.findCandidateComponents("com/thoughtworks");
    List<Class> reflectionsSubTypesOf = candidateComponents.stream().map(beanDefinition -> beanDefinition.getBeanClassName()).map(s -> {
        try {
            return Class.forName(s);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }).collect(Collectors.toList());

    reflectionsSubTypesOf.removeIf(this::isNotAConcrete_NonTest_MaterialConfigImplementation);

    List<Class> allExpectedMaterialConfigImplementations = allMaterialConfigsWhichAreDataPointsInThisTest();

    assertThatAllMaterialConfigsInCodeAreTestedHere(reflectionsSubTypesOf, allExpectedMaterialConfigImplementations);
}
 
源代码24 项目: DataGenerator   文件: TransformerUtils.java
public static Set<Class<FunctionTransformation>> findFunctionTransformers(String basePackage) {
    ClassPathScanner classPathScanner = new SimpleClassPathScanner(basePackage);
    classPathScanner.addIncludeFilter(new AssignableTypeFilter(FunctionTransformation.class));
    for(BeanDefinition bd : classPathScanner.findComponents()) {
        try {
            Class cl = Class.forName(bd.getBeanClassName());
            if(!Modifier.isAbstract(cl.getModifiers())) {
                logger.debug("Adding transformer function {}", cl);
                functionTransformerClasses.add(cl);
            } else {
                logger.debug("Ignoring transformer function {}", cl);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    return functionTransformerClasses;
}
 
源代码25 项目: usergrid   文件: Schema.java
@SuppressWarnings("unchecked")
public void scanEntities() {
    synchronized ( entitiesScanPath ) {
        for ( String path : entitiesScanPath ) {
            ClassPathScanningCandidateComponentProvider provider =
                    new ClassPathScanningCandidateComponentProvider( true );
            provider.addIncludeFilter( new AssignableTypeFilter( TypedEntity.class ) );

            Set<BeanDefinition> components = provider.findCandidateComponents( path );
            for ( BeanDefinition component : components ) {
                try {
                    Class<?> cls = Class.forName( component.getBeanClassName() );
                    if ( Entity.class.isAssignableFrom( cls ) ) {
                        registerEntity( ( Class<? extends Entity> ) cls );
                    }
                }
                catch ( ClassNotFoundException e ) {
                    logger.error( "Unable to get entity class ", e );
                }
            }
            registerEntity( DynamicEntity.class );
        }
    }
}
 
/**
 * Determine if the specified include {@link TypeFilter} is supported by the index.
 * @param filter the filter to check
 * @return whether the index supports this include filter
 * @since 5.0
 * @see #extractStereotype(TypeFilter)
 */
private boolean indexSupportsIncludeFilter(TypeFilter filter) {
	if (filter instanceof AnnotationTypeFilter) {
		Class<? extends Annotation> annotation = ((AnnotationTypeFilter) filter).getAnnotationType();
		return (AnnotationUtils.isAnnotationDeclaredLocally(Indexed.class, annotation) ||
				annotation.getName().startsWith("javax."));
	}
	if (filter instanceof AssignableTypeFilter) {
		Class<?> target = ((AssignableTypeFilter) filter).getTargetType();
		return AnnotationUtils.isAnnotationDeclaredLocally(Indexed.class, target);
	}
	return false;
}
 
/**
 * Extract the stereotype to use for the specified compatible filter.
 * @param filter the filter to handle
 * @return the stereotype in the index matching this filter
 * @since 5.0
 * @see #indexSupportsIncludeFilter(TypeFilter)
 */
@Nullable
private String extractStereotype(TypeFilter filter) {
	if (filter instanceof AnnotationTypeFilter) {
		return ((AnnotationTypeFilter) filter).getAnnotationType().getName();
	}
	if (filter instanceof AssignableTypeFilter) {
		return ((AssignableTypeFilter) filter).getTargetType().getName();
	}
	return null;
}
 
@SuppressWarnings("unchecked")
protected TypeFilter createTypeFilter(Element element, @Nullable ClassLoader classLoader,
		ParserContext parserContext) throws ClassNotFoundException {

	String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE);
	String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE);
	expression = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(expression);
	if ("annotation".equals(filterType)) {
		return new AnnotationTypeFilter((Class<Annotation>) ClassUtils.forName(expression, classLoader));
	}
	else if ("assignable".equals(filterType)) {
		return new AssignableTypeFilter(ClassUtils.forName(expression, classLoader));
	}
	else if ("aspectj".equals(filterType)) {
		return new AspectJTypeFilter(expression, classLoader);
	}
	else if ("regex".equals(filterType)) {
		return new RegexPatternTypeFilter(Pattern.compile(expression));
	}
	else if ("custom".equals(filterType)) {
		Class<?> filterClass = ClassUtils.forName(expression, classLoader);
		if (!TypeFilter.class.isAssignableFrom(filterClass)) {
			throw new IllegalArgumentException(
					"Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression);
		}
		return (TypeFilter) BeanUtils.instantiateClass(filterClass);
	}
	else {
		throw new IllegalArgumentException("Unsupported filter type: " + filterType);
	}
}
 
private void testCustomAssignableTypeIncludeFilter(ClassPathScanningCandidateComponentProvider provider,
		Class<? extends BeanDefinition> expectedBeanDefinitionType) {
	provider.addIncludeFilter(new AssignableTypeFilter(FooService.class));
	Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
	// Interfaces/Abstract class are filtered out automatically.
	assertTrue(containsBeanClass(candidates, AutowiredQualifierFooService.class));
	assertTrue(containsBeanClass(candidates, FooServiceImpl.class));
	assertTrue(containsBeanClass(candidates, ScopedProxyTestBean.class));
	assertEquals(3, candidates.size());
	assertBeanDefinitionType(candidates, expectedBeanDefinitionType);
}
 
@Test
public void customNotSupportedIncludeFilterUseScan() {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
	provider.setResourceLoader(new DefaultResourceLoader(TEST_BASE_CLASSLOADER));
	provider.addIncludeFilter(new AssignableTypeFilter(FooDao.class));
	Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
	assertTrue(containsBeanClass(candidates, StubFooDao.class));
	assertEquals(1, candidates.size());
	assertBeanDefinitionType(candidates, ScannedGenericBeanDefinition.class);
}
 
 类所在包
 类方法
 同包方法