Java Code Examples for org.reflections.Reflections#getSubTypesOf()

The following examples show how to use org.reflections.Reflections#getSubTypesOf() . 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: ActivitySerDeTest.java    From streams with Apache License 2.0 6 votes vote down vote up
/**
 * 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 2
Source File: OptionsDefaultConstructorsTest.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Test default constructors and set options.
 * @throws InstantiationException the instantiation exception
 * @throws IllegalAccessException the illegal access exception
 */
@Test
public void testDefaultConstructorsAndSetOptions()
		throws InstantiationException, IllegalAccessException {
	Reflections reflections = new Reflections(
		"com.perforce.p4java.option");
	Set<Class<? extends Options>> subTypes = 
	           reflections.getSubTypesOf(Options.class);
	for (Class<? extends Options> subtype : subTypes) {
		if (!subtype.getName().contains("Test")) {
			Options options = subtype.newInstance();
			options.setOptions("one");
			assertTrue(options.getOptions() != null);
			assertTrue(options.getOptions().size() == 1);
			assertTrue(options.getOptions().contains("one"));
		}
	}
}
 
Example 3
Source File: TtfInstructionParser.java    From FontVerter with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void initInstructionTypes() throws IllegalAccessException, InstantiationException {
    // uses reflection to grab all TtfInstruction implementations than grabs their code ranges and adds an entry
    // into a code=> instruction class map to be used when creating instruction objects from a code when parsing
    // to remove the need for a giant if/switch block
    if (instructionTypes.isEmpty()) {
        Reflections reflections = new Reflections("org.mabb.fontverter");
        Set<Class<? extends TtfInstruction>> adapterClasses = reflections.getSubTypesOf(TtfInstruction.class);
        List<Class> instructionClasses = Arrays.asList(adapterClasses.toArray(new Class[adapterClasses.size()]));

        for (Class typeOn : instructionClasses) {
            // instiante a test object once to grab it's code ranges to use in code=>instruction class type map
            TtfInstruction instructOn = (TtfInstruction) typeOn.newInstance();

            int[] range = instructOn.getCodeRanges();
            if (range.length == 1)
                instructionTypes.put(range[0], typeOn);
            else {
                for (int i = range[0]; i <= range[1]; i++)
                    instructionTypes.put(i, typeOn);
            }
        }
    }
}
 
Example 4
Source File: StateHandleSerializationTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void ensureStateHandlesHaveSerialVersionUID() {
	try {
		Reflections reflections = new Reflections("org.apache.flink");

		// check all state handles

		@SuppressWarnings("unchecked")
		Set<Class<?>> stateHandleImplementations = (Set<Class<?>>) (Set<?>)
				reflections.getSubTypesOf(StateObject.class);

		for (Class<?> clazz : stateHandleImplementations) {
			validataSerialVersionUID(clazz);
		}
	}
	catch (Exception e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example 5
Source File: StreamsJacksonModule.java    From streams with Apache License 2.0 6 votes vote down vote up
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 6
Source File: Civs.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
private void initCommands() {
    Reflections reflections = new Reflections("org.redcastlemedia.multitallented.civs.commands");
    Set<Class<? extends CivCommand>> commands = reflections.getSubTypesOf(CivCommand.class);
    for (Class<? extends CivCommand> currentCommandClass : commands) {
        try {
            CivCommand currentCommand = currentCommandClass.newInstance();
            for (String key : currentCommandClass.getAnnotation(CivsCommand.class).keys()) {
                commandList.put(key, currentCommand);
            }
        } catch (Exception e) {
            Civs.logger.log(Level.SEVERE, "Unable to load {0} class", currentCommandClass.getName());
            Civs.logger.log(Level.SEVERE, "Exception generated", e);
        }
    }
}
 
Example 7
Source File: SVCHandler.java    From ARMStrong with Mozilla Public License 2.0 5 votes vote down vote up
public void findIOSyscalls() {
	Reflections reflections = new Reflections("projetarm_v2.simulator.core.syscalls.io");

	Set<Class<? extends SVCIOCall>> calls = reflections.getSubTypesOf(SVCIOCall.class);
	
	for (Class<? extends SVCIOCall> classCall : calls) {
		try {
			SVCCall call = (SVCIOCall)(classCall.getDeclaredConstructor(Cpu.class, FileDescriptors.class).newInstance(this.cpu, this.fileDescriptors));
			this.interruptVector.put(call.getSvcNumber(),call);
		} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {}
	}
}
 
Example 8
Source File: ObjectPayload.java    From ysoserial-modified with MIT License 5 votes vote down vote up
public static Set<Class<? extends ObjectPayload>> getPayloadClasses () {
    final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName());
    final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class);
    for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) {
        Class<? extends ObjectPayload> pc = iterator.next();
        if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) {
            iterator.remove();
        }
    }
    return payloadTypes;
}
 
Example 9
Source File: EventDetectionUI.java    From SONDY with GNU General Public License v3.0 5 votes vote down vote up
public final void updateAvailableMethods(){
    Reflections reflections = new Reflections("main.java.fr.ericlab.sondy.algo.eventdetection");    
    Set<Class<? extends EventDetectionMethod>> classes = reflections.getSubTypesOf(EventDetectionMethod.class);   
    for(Class<? extends EventDetectionMethod> aClass : classes){
        try {
            EventDetectionMethod method = (EventDetectionMethod) Class.forName(aClass.getName()).newInstance();
            methodList.getItems().add(method.getName());
            methodMap.put(method.getName(),aClass.getName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            Logger.getLogger(EventDetectionUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
 
Example 10
Source File: ObjectMapperBuilder.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
private void registerCustomSerializers(Reflections reflections, SimpleModule jacksonModule) {
    Set<Class<? extends JsonSerializer>> customSerializers = reflections.getSubTypesOf(JsonSerializer.class);
    for (Class<? extends JsonSerializer> customSerializer : customSerializers) {
        Class<?> objectClass = TypeResolver.resolveRawArgument(JsonSerializer.class,customSerializer);
        try {
            jacksonModule.addSerializer(objectClass, customSerializer.newInstance());
        } catch(Exception e) {
            logger.warn("Failed to create Custom Jackson Serializer: {}",customSerializer.getName(),e);
        }
    }
}
 
Example 11
Source File: StatefulFactory.java    From statefulj with Apache License 2.0 5 votes vote down vote up
/**
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
private void loadEndpointBinders(Reflections reflections, Map<String, EndpointBinder> binders) throws InstantiationException,
		IllegalAccessException {
	Set<Class<? extends EndpointBinder>> endpointBinders = reflections.getSubTypesOf(EndpointBinder.class);
	for(Class<?> binderClass : endpointBinders) {
		if (!Modifier.isAbstract(binderClass.getModifiers())) {
			EndpointBinder binder = (EndpointBinder)binderClass.newInstance();
			binders.put(binder.getKey(), binder);
		}
	}
}
 
Example 12
Source File: ClassUtils.java    From jkes with Apache License 2.0 5 votes vote down vote up
static Set<Class<?>> getClasses(String packageName) {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
            .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName))));

    Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
    return classes;
}
 
Example 13
Source File: StatefulFactory.java    From statefulj with Apache License 2.0 5 votes vote down vote up
/**
 * @param reflections
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
private void loadPersistenceSupportBeanFactories(Reflections reflections, Map<Class<?>, PersistenceSupportBeanFactory> persistenceFactories)
		throws InstantiationException, IllegalAccessException {
	Set<Class<? extends PersistenceSupportBeanFactory>> persistenceFactoryTypes = reflections.getSubTypesOf(PersistenceSupportBeanFactory.class);
	for(Class<?> persistenceFactoryType : persistenceFactoryTypes) {
		if (!Modifier.isAbstract(persistenceFactoryType.getModifiers())) {
			PersistenceSupportBeanFactory factory = (PersistenceSupportBeanFactory)persistenceFactoryType.newInstance();
			Class<?> key = factory.getKey();
			if (key != null) {
				persistenceFactories.put(key, factory);
			}
		}
	}
}
 
Example 14
Source File: ApiWrapperUtil.java    From wekaDeeplearning4j with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get all subclasses of the given class.
 */
private static <T extends ApiWrapper<V>, V> Set<Class<? extends T>> getSubclassesOf(
    Class<T> cls, String packageName) {
  Reflections reflections = new Reflections(packageName);
  return reflections.getSubTypesOf(cls);
}
 
Example 15
Source File: ClasspathUtils.java    From gridgo with MIT License 4 votes vote down vote up
public static <Type> void scanForSubTypes(Reflections reflections, Class<Type> superType,
        Consumer<Class<? extends Type>> acceptor) {
    var types = reflections.getSubTypesOf(superType);
    types.forEach(acceptor);
}
 
Example 16
Source File: ReflectionBasedJsr303AnnotationTrollerBase.java    From backstopper with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes the instance based on what is returned by {@link #ignoreAllAnnotationsAssociatedWithTheseProjectClasses()}
 * and {@link #specificAnnotationDeclarationExclusionsForProject()}. This is time consuming and should only be done
 * once per project if possible - see the usage info in the {@link ReflectionBasedJsr303AnnotationTrollerBase}
 * class-level javadocs.
 *
 * <p>The given set of extra packages for constraint annotation searching will be passed into {@link
 * #getFinalPackagesToSearchForConstraintAnnotations(Set)} to generate the final set of packages that are searched.
 * If you don't want the {@link #DEFAULT_CONSTRAINT_SEARCH_PACKAGES} default packages to be searched you can
 * override {@link #getDefaultPackagesToSearchForConstraintAnnotations()}.
 */
public ReflectionBasedJsr303AnnotationTrollerBase(Set<String> extraPackagesForConstraintAnnotationSearch) {

    /*
     * Set up the {@link #ignoreAllAnnotationsAssociatedWithTheseClasses} and
     * {@link #specificAnnotationDeclarationsExcludedFromStrictMessageRequirement} fields so we know which
     * annotations are project-relevant vs. unit-test-only.
     */
    ignoreAllAnnotationsAssociatedWithTheseClasses =
        new ArrayList<>(setupIgnoreAllAnnotationsAssociatedWithTheseClasses());
    specificAnnotationDeclarationsExcludedFromStrictMessageRequirement =
        new ArrayList<>(setupSpecificAnnotationDeclarationExclusions());

    /*
     * Set up the {@link #reflections}, {@link #constraintAnnotationClasses}, and
     * {@link #allConstraintAnnotationsMasterList} fields. This is where the crazy reflection magic happens to troll
     * the project for the JSR 303 annotation declarations.
     */
    // Create the ConfigurationBuilder to search the relevant set of packages.
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    for (String packageToAdd : getFinalPackagesToSearchForConstraintAnnotations(
        extraPackagesForConstraintAnnotationSearch)) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(packageToAdd));
    }

    // Create the Reflections object so it scans for all validation annotations we care about and all project
    //      classes that might have annotations on them.
    reflections = new Reflections(configurationBuilder.setScanners(
        new SubTypesScanner(), new MethodParameterScanner(), new TypeAnnotationsScanner(),
        new MethodAnnotationsScanner(), new FieldAnnotationsScanner()
    ));

    // Gather the list of all JSR 303 validation annotations in the project. Per the JSR 303 spec this is any
    //      annotation class type that is marked with @Constraint.
    constraintAnnotationClasses = new ArrayList<>();
    for (Class<?> constraintAnnotatedType : reflections.getTypesAnnotatedWith(Constraint.class, true)) {
        if (constraintAnnotatedType.isAnnotation()) {
            //noinspection unchecked
            constraintAnnotationClasses.add((Class<? extends Annotation>) constraintAnnotatedType);
        }
    }

    // We're not done gathering validation annotations though, unfortunately. JSR 303 also says that *any*
    //      annotation (whether it is a Constraint or not) that has a value field that returns an array of actual
    //      Constraints is treated as a "multi-value constraint", and the validation processor will run each
    //      of the Constraints in the array as if they were declared separately on the annotated element. Therefore,
    //      we have to dig through all the annotations in the project, find any that fall into this "multi-value
    //      constraint" category, and include them in our calculations.
    for (Class<? extends Annotation> annotationClass : reflections.getSubTypesOf(Annotation.class)) {
        if (isMultiValueConstraintClass(annotationClass))
            constraintAnnotationClasses.add(annotationClass);
    }

    // Setup the master constraint list
    allConstraintAnnotationsMasterList =
        new ArrayList<>(setupAllConstraintAnnotationsMasterList(reflections, constraintAnnotationClasses));

    /*
     * Finally use the info we've gathered/constructed previously to populate the
     * {@link #projectRelevantConstraintAnnotationsExcludingUnitTestsList} field, which is the main chunk of data
     * that extensions of this class will care about.
     */
    projectRelevantConstraintAnnotationsExcludingUnitTestsList = Collections.unmodifiableList(
        getSubAnnotationListUsingExclusionFilters(allConstraintAnnotationsMasterList,
                                                  ignoreAllAnnotationsAssociatedWithTheseClasses,
                                                  specificAnnotationDeclarationsExcludedFromStrictMessageRequirement));
}
 
Example 17
Source File: AddMehodClassFactory.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
public void addExpender(Reflections reflections, Class expenderInterface) throws CannotCompileException, NotFoundException {
    Set<Class> set = reflections.getSubTypesOf(expenderInterface);
    for (Class aClass : set) {
        addExpender(aClass);
    }
}
 
Example 18
Source File: ResponseTest.java    From java-telegram-bot-api with Apache License 2.0 4 votes vote down vote up
@Before
public void setClasses() {
    Reflections reflections = new Reflections(BaseResponse.class.getPackage().getName());
    classes = reflections.getSubTypesOf(BaseResponse.class);
    classes.add(BaseResponse.class);
}
 
Example 19
Source File: ApiWrapperUtil.java    From wekaDeeplearning4j with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get all subclasses of the given class.
 */
private static <T extends ApiWrapper<V>, V> Set<Class<? extends T>> getSubclassesOf(
    Class<T> cls, String packageName) {
  Reflections reflections = new Reflections(packageName);
  return reflections.getSubTypesOf(cls);
}
 
Example 20
Source File: ReflectUtils.java    From zkdoctor with Apache License 2.0 2 votes vote down vote up
/**
 * 获取所有监控类
 * 监控类要求:
 * 1、为MonitorBase子类
 * 2、位于com.ucar.zkdoctor.service.monitor.detail包下
 * 3、重写monitor()与init()方法
 * 即可
 *
 * @param basePackage 指定包
 * @return
 */
public static Set<Class<? extends MonitorBase>> getMonitorClassesSet(String basePackage) {
    Reflections reflections = new Reflections(basePackage);
    return reflections.getSubTypesOf(MonitorBase.class);
}