Tabnine Logo
Reflections
Code IndexAdd Tabnine to your IDE (free)

How to use
Reflections
in
org.reflections

Best Java code snippets using org.reflections.Reflections (Showing top 20 results out of 3,600)

Refine searchRefine arrow

  • Store
  • ConfigurationBuilder
  • ClasspathHelper
  • SubTypesScanner
  • Multimap
  • TypeAnnotationsScanner
  • ReflectionUtils
  • FilterBuilder
  • Sets
origin: ronmamo/reflections

public Reflections read(InputStream inputStream) {
  Reflections reflections;
  try {
    Constructor<Reflections> constructor = Reflections.class.getDeclaredConstructor();
    constructor.setAccessible(true);
    reflections = constructor.newInstance();
  } catch (Exception e) {
    reflections = new Reflections(new ConfigurationBuilder());
  }
  try {
    Document document = new SAXReader().read(inputStream);
    for (Object e1 : document.getRootElement().elements()) {
      Element index = (Element) e1;
      for (Object e2 : index.elements()) {
        Element entry = (Element) e2;
        Element key = entry.element("key");
        Element values = entry.element("values");
        for (Object o3 : values.elements()) {
          Element value = (Element) o3;
          reflections.getStore().getOrCreate(index.getName()).put(key.getText(), value.getText());
        }
      }
    }
  } catch (DocumentException e) {
    throw new ReflectionsException("could not read.", e);
  } catch (Throwable e) {
    throw new RuntimeException("Could not read. Make sure relevant dependencies exist on classpath.", e);
  }
  return reflections;
}
origin: stackoverflow.com

Reflections reflections = new Reflections("my.project.prefix");
Set<Class<? extends Object>> allClasses = 
  reflections.getSubTypesOf(Object.class);
origin: swagger-api/swagger-core

@Override
public Set<Class<?>> classes() {
  ConfigurationBuilder config = new ConfigurationBuilder();
  Set<String> acceptablePackages = new HashSet<String>();
  Set<String> resourceClasses = new HashSet<String>();
      if (!isIgnored(pkg)) {
        acceptablePackages.add(pkg);
        config.addUrls(ClasspathHelper.forPackage(pkg));
  config.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
  final Reflections reflections = new Reflections(config);
  Set<Class<?>> classes = reflections.getTypesAnnotatedWith(OpenAPIDefinition.class);
origin: stackoverflow.com

 Reflections reflections = new Reflections("my.project.prefix");

Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);

Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class);
origin: ninjaframework/ninja

/**
 * Searches for Methods that have either a Path Annotation or a HTTP-Method Annotation
 */
@SuppressWarnings("unchecked")
private Set<Method> findControllerMethods() {
  Set<Method> methods = Sets.newLinkedHashSet();
  methods.addAll(reflections.getMethodsAnnotatedWith(Path.class));
  Reflections annotationReflections = new Reflections("", new TypeAnnotationsScanner(), new SubTypesScanner());
  for (Class<?> httpMethod : annotationReflections.getTypesAnnotatedWith(HttpMethod.class)) {
    if (httpMethod.isAnnotation()) {
      methods.addAll(reflections.getMethodsAnnotatedWith((Class<? extends Annotation>) httpMethod));
    }
  }
  return methods;
}
origin: org.deeplearning4j/deeplearning4j-play

private List<UIModule> getCustomUIModules(List<Class<?>> excludeClasses) {
  //Scan classpath for UI module instances, but ignore the 'excludeClasses' classes
  List<String> classNames = Collections.singletonList(UIModule.class.getName());
  Reflections reflections = new Reflections();
  org.reflections.Store store = reflections.getStore();
  Iterable<String> subtypesByName =
          store.getAll(org.reflections.scanners.SubTypesScanner.class.getSimpleName(), classNames);
  Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName));
  List<Class<?>> toCreate = new ArrayList<>();
  for (Class<?> c : subtypeClasses) {
    if (excludeClasses.contains(c))
      continue;;
    toCreate.add(c);
  }
  List<UIModule> ret = new ArrayList<>(toCreate.size());
  for (Class<?> c : toCreate) {
    UIModule m;
    try {
      m = (UIModule) c.newInstance();
    } catch (Exception e) {
      log.warn("Could not create instance of custom UIModule of type {}; skipping", c, e);
      continue;
    }
    log.debug("Created instance of custom UI module: {}", c);
    ret.add(m);
  }
  return ret;
}
origin: org.datavec/datavec-data-image

List<Class<?>> classesList = Arrays.<Class<?>>asList();
Collection<URL> urls = ClasspathHelper.forClassLoader();
List<URL> scanUrls = new ArrayList<>();
for (URL u : urls) {
Reflections reflections = new Reflections(
        new ConfigurationBuilder().filterInputsBy(new FilterBuilder().exclude("^(?!.*\\.class$).*$") //Consider only .class files (to avoid debug messages etc. on .dlls, etc
                .exclude("^org.reflections.*").exclude("^ch.qos.*") //Logback
        ).addUrls(scanUrls).setScanners(new DataVecSubTypesScanner(interfaces, classesList)));
org.reflections.Store store = reflections.getStore();
Iterable<String> subtypesByName = store.getAll(DataVecSubTypesScanner.class.getSimpleName(), classNames);
Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName));
subtypesClassCache = new HashSet<>();
for (Class<?> c : subtypeClasses) {
origin: com.github.markusmo3.urm/urm-core

private static Set<Class<?>> getClasses(ClassLoader classLoader, String packageName) {
  List<ClassLoader> classLoadersList = new LinkedList<>();
  classLoadersList.add(ClasspathHelper.contextClassLoader());
  classLoadersList.add(ClasspathHelper.staticClassLoader());
  if (classLoader != null) {
    classLoadersList.add(classLoader);
  }
  classLoaders = classLoadersList.toArray(new ClassLoader[0]);
  FilterBuilder filter = new FilterBuilder()
      .include(FilterBuilder.prefix(packageName));
  if (!isAllowFindingInternalClasses()) {
    filter.exclude(FilterBuilder.prefix(URM_PACKAGE));
  }
  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setScanners(new SubTypesScanner(false /* don't exclude Object.class */),
          new ResourcesScanner())
      .setUrls(ClasspathHelper.forPackage(packageName, classLoaders))
      .filterInputsBy(filter)
      .addClassLoaders(classLoadersList)
  );
  Multimap<String, String> mmap = reflections.getStore().get(SubTypesScanner.class.getSimpleName());
  return Sets.newHashSet(ReflectionUtils.forNames(mmap.values(), classLoadersList.toArray(new ClassLoader[0])));
}
origin: eventsourcing/es4j

Set<Class<? extends T>> scan(Class<? extends T> aClass) {
  Configuration configuration = ConfigurationBuilder.build((Object[]) packages).addClassLoaders(classLoaders)
                           .addScanners(new AssignableScanner(aClass));
  Reflections reflections = new Reflections(configuration);
  Predicate<Class<? extends T>> classPredicate = klass ->
      Modifier.isPublic(klass.getModifiers()) &&
          (!klass.isMemberClass() || (klass.isMemberClass() && Modifier
              .isStatic(klass.getModifiers()))) &&
          !Modifier.isInterface(klass.getModifiers()) &&
          !Modifier.isAbstract(klass.getModifiers());
  HashSet<Class<? extends T>> subtypes = Sets.newHashSet(
      ReflectionUtils.forNames(
          reflections.getStore()
                .getAll(AssignableScanner.class.getSimpleName(),
                    Collections.singletonList(aClass.getName())), classLoaders));
  return subtypes.stream().filter(classPredicate).collect(Collectors.toSet());
}
origin: Evolveum/midpoint

ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setScanners(new SubTypesScanner(false));
builder.setUrls(ClasspathHelper.forPackage(packageName, LOGGER.getClass().getClassLoader()));
builder.setInputsFilter(new FilterBuilder().includePackage(packageName));
Reflections reflections = new Reflections(builder);
Multimap<String, String> map = reflections.getStore().get(SubTypesScanner.class.getSimpleName());
Set<String> types = new HashSet<>();
for (String key : map.keySet()) {
  Collection<String> col = map.get(key);
  if (col == null) {
    continue;
origin: ronmamo/reflections

Serializer serializer = optionalSerializer != null && optionalSerializer.length == 1 ? optionalSerializer[0] : new XmlSerializer();
Collection<URL> urls = ClasspathHelper.forPackage(packagePrefix);
if (urls.isEmpty()) return null;
long start = System.currentTimeMillis();
final Reflections reflections = new Reflections();
Iterable<Vfs.File> files = Vfs.findFiles(urls, packagePrefix, resourceNameFilter);
for (final Vfs.File file : files) {
  try {
    inputStream = file.openInputStream();
    reflections.merge(serializer.read(inputStream));
  } catch (IOException e) {
    throw new ReflectionsException("could not merge " + file, e);
  Store store = reflections.getStore();
  int keys = 0;
  int values = 0;
  for (String index : store.keySet()) {
    keys += store.get(index).keySet().size();
    values += store.get(index).size();
origin: thinkaurelius/titan

org.reflections.Configuration rc = new org.reflections.util.ConfigurationBuilder()
  .setUrls(scanUrls)
  .setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
Reflections reflections = new Reflections(rc);
for (Class<?> c : reflections.getTypesAnnotatedWith(PreInitializeConfigOptions.class)) {
  try {
    loadCount += loadSingleClassUnsafe(c);
origin: apache/incubator-gobblin

/**
 * 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);
}
origin: org.xwiki.commons/xwiki-commons-filter-test

public Collection<TestConfiguration> generateData(String testPackage, String pattern)
{
  Reflections reflections =
    new Reflections(new ConfigurationBuilder().setScanners(new ResourcesScanner())
      .setUrls(ClasspathHelper.forPackage(""))
      .filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix(testPackage))));
  Collection<TestConfiguration> data = new ArrayList<TestConfiguration>();
  for (String testResourceName : reflections.getResources(Pattern.compile(pattern))) {
    data.addAll(parseSingleResource(testResourceName));
  }
  return data;
}
origin: juanmf/Java2PlantUML

private static Collection<? extends Class<?>> getPackageTypes(String packageToPase, Collection<URL> urls) {
  Set<Class<?>> classes = new HashSet<>();
  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setScanners(new SubTypesScanner(false /* exclude Object.class */), new ResourcesScanner(), new TypeElementsScanner())
      .setUrls(urls)
      .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageToPase)).exclude("java.*")));
  Set<String> types;
  types = reflections.getStore().get("TypeElementsScanner").keySet();
  for (String type: types) {
    Class<?> aClass = TypesHelper.loadClass(type, CLASS_LOADER);
    boolean wantedElement = StringUtils.startsWith(type, packageToPase);
    if (null != aClass && wantedElement) {
      logger.log(Level.INFO, "looking up for type: " + type);
      classes.add(aClass);
    }
  }
  return classes;
}
origin: swagger-api/swagger-core

ConfigurationBuilder config = new ConfigurationBuilder();
Set<String> acceptablePackages = new HashSet<String>();
Set<Class<?>> output = new HashSet<Class<?>>();
    if (!isIgnored(pkg)) {
      acceptablePackages.add(pkg);
      config.addUrls(ClasspathHelper.forPackage(pkg));
  allowAllPackages = true;
config.filterInputsBy(new FilterBuilder().exclude(".*json").exclude(".*yaml"));
config.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
final Reflections reflections;
reflections = new Reflections(config);
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(javax.ws.rs.Path.class);
classes.addAll(reflections.getTypesAnnotatedWith(OpenAPIDefinition.class));
origin: querydsl/querydsl

/**
 * Return the classes from the given package and subpackages using the supplied classloader
 *
 * @param classLoader classloader to be used
 * @param pkg package to scan
 * @return set of found classes
 * @throws IOException
 */
public static Set<Class<?>> scanPackage(ClassLoader classLoader, String pkg) throws IOException {
  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .addUrls(ClasspathHelper.forPackage(pkg, classLoader))
      .addClassLoader(classLoader)
      .setScanners(new SubTypesScanner(false)));
  Set<Class<?>> classes = new HashSet<Class<?>>();
  for (String typeNames : reflections.getStore().get(SubTypesScanner.class.getSimpleName()).values()) {
    Class<?> clazz = safeClassForName(classLoader, typeNames);
    if (clazz != null) {
      classes.add(clazz);
    }
  }
  return classes;
}
origin: MorphiaOrg/morphia

final ConfigurationBuilder conf = new ConfigurationBuilder();
conf.setScanners(new TypeElementsScanner(), new TypeAnnotationsScanner());
s.addAll(ClasspathHelper.forClassLoader());
s.addAll(ClasspathHelper.forJavaClassPath());
final Iterator<URL> iterator = s.iterator();
while (iterator.hasNext()) {
conf.setUrls(new ArrayList<URL>(s));
conf.filterInputsBy(localPredicate);
conf.addScanners(new SubTypesScanner());
final Reflections r = new Reflections(conf);
final Set<Class<?>> entities = r.getTypesAnnotatedWith(Entity.class);
for (final Class<?> c : entities) {
  m.map(c);
origin: knightliao/disconf

FilterBuilder filterBuilder = new FilterBuilder().includePackage(Constants.DISCONF_PACK_NAME);
  filterBuilder = filterBuilder.includePackage(packName);
  Set<URL> urls = ClasspathHelper.forPackage(packName);
  urlTotals.addAll(urls);
Reflections reflections = new Reflections(new ConfigurationBuilder().filterInputsBy(filter)
    .setScanners(new SubTypesScanner().filterResultsBy(filter),
        new TypeAnnotationsScanner()
            .filterResultsBy(filter),
        new FieldAnnotationsScanner()
            .filterResultsBy(filter),
origin: yahoo/elide

  /**
   * Get all the entities in a package.
   *
   * @param packageName Package name
   * @return All entities found in package.
   */
  public static HashSet<Class> getAllEntities(String packageName) {
    return new HashSet<>(new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner())
        .setUrls(ClasspathHelper.forClassLoader(ClassLoader.getSystemClassLoader()))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName))))
        .getTypesAnnotatedWith(Entity.class));
  }
}
org.reflectionsReflections

Javadoc

Reflections one-stop-shop object

Reflections scans your classpath, indexes the metadata, allows you to query it on runtime and may save and collect that information for many modules within your project.

Using Reflections you can query your metadata such as:

  • get all subtypes of some type
  • get all types/constructors/methods/fields annotated with some annotation, optionally with annotation parameters matching
  • get all resources matching matching a regular expression
  • get all methods with specific signature including parameters, parameter annotations and return type
  • get all methods parameter names
  • get all fields/methods/constructors usages in code

A typical use of Reflections would be:

 
Reflections reflections = new Reflections("my.project.prefix"); 
Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class); 
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class); 

Basically, to use Reflections first instantiate it with one of the constructors, then depending on the scanners, use the convenient query methods:

 
Reflections reflections = new Reflections("my.package.prefix"); 
//or 
Reflections reflections = new Reflections(ClasspathHelper.forPackage("my.package.prefix"), 
new SubTypesScanner(), new TypesAnnotationScanner(), new FilterBuilder().include(...), ...); 
//or using the ConfigurationBuilder 
new Reflections(new ConfigurationBuilder() 
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("my.project.prefix"))) 
.setUrls(ClasspathHelper.forPackage("my.project.prefix")) 
.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...)); 
And then query, for example:
 
Set<Class<? extends Module>> modules = reflections.getSubTypesOf(com.google.inject.Module.class); 
Set<Class<?>> singletons =             reflections.getTypesAnnotatedWith(javax.inject.Singleton.class); 
Set<String> properties =       reflections.getResources(Pattern.compile(".*\\.properties")); 
Set<Constructor> injectables = reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class); 
Set<Method> deprecateds =      reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class); 
Set<Field> ids =               reflections.getFieldsAnnotatedWith(javax.persistence.Id.class); 
Set<Method> someMethods =      reflections.getMethodsMatchParams(long.class, int.class); 
Set<Method> voidMethods =      reflections.getMethodsReturn(void.class); 
Set<Method> pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(PathParam.class); 
Set<Method> floatToString =    reflections.getConverters(Float.class, String.class); 
List<String> parameterNames =  reflections.getMethodsParamNames(Method.class); 
Set<Member> fieldUsage =       reflections.getFieldUsage(Field.class); 
Set<Member> methodUsage =      reflections.getMethodUsage(Method.class); 
Set<Member> constructorUsage = reflections.getConstructorUsage(Constructor.class); 

You can use other scanners defined in Reflections as well, such as: SubTypesScanner, TypeAnnotationsScanner (both default), ResourcesScanner, MethodAnnotationsScanner, ConstructorAnnotationsScanner, FieldAnnotationsScanner, MethodParameterScanner, MethodParameterNamesScanner, MemberUsageScanner or any custom scanner.

Use #getStore() to access and query the store directly

In order to save the store metadata, use #save(String) or #save(String,org.reflections.serializers.Serializer)for example with org.reflections.serializers.XmlSerializer or org.reflections.serializers.JavaCodeSerializer

In order to collect pre saved metadata and avoid re-scanning, use #collect(String,com.google.common.base.Predicate,org.reflections.serializers.Serializer...)}

Make sure to scan all the transitively relevant packages.
for instance, given your class C extends B extends A, and both B and A are located in another package than C, when only the package of C is scanned - then querying for sub types of A returns nothing (transitive), but querying for sub types of B returns C (direct). In that case make sure to scan all relevant packages a priori.

For Javadoc, source code, and more information about Reflections Library, see http://github.com/ronmamo/reflections/

Most used methods

  • <init>
    a convenient constructor for Reflections, where given Object... parameter types can be either: * St
  • getSubTypesOf
    gets all sub types in hierarchy of a given typedepends on SubTypesScanner configured
  • getTypesAnnotatedWith
    get types annotated with a given annotation, both classes and annotations, including annotation memb
  • getResources
  • getMethodsAnnotatedWith
    get all methods annotated with a given annotation, including annotation member values matchingdepend
  • getStore
    returns the org.reflections.Store used for storing and querying the metadata
  • getFieldsAnnotatedWith
    get all methods annotated with a given annotation, including annotation member values matchingdepend
  • merge
    merges a Reflections instance metadata into this instance
  • collect
  • getConstructorsAnnotatedWith
    get all constructors annotated with a given annotation, including annotation member values matchingd
  • getConstructorsWithAnyParamAnnotated
    get constructors with any parameter annotated with given annotation, including annotation member val
  • getMethodsWithAnyParamAnnotated
    get methods with any parameter annotated with given annotation, including annotation member values m
  • getConstructorsWithAnyParamAnnotated,
  • getMethodsWithAnyParamAnnotated,
  • save,
  • scan,
  • getAllAnnotated,
  • index,
  • loaders,
  • expandSuperTypes,
  • expandSupertypes,
  • getConfiguration

Popular in Java

  • Finding current android device location
  • getExternalFilesDir (Context)
  • getSupportFragmentManager (FragmentActivity)
  • onRequestPermissionsResult (Fragment)
  • BufferedReader (java.io)
    Wraps an existing Reader and buffers the input. Expensive interaction with the underlying reader is
  • DateFormat (java.text)
    Formats or parses dates and times.This class provides factories for obtaining instances configured f
  • HashMap (java.util)
    HashMap is an implementation of Map. All optional operations are supported.All elements are permitte
  • Set (java.util)
    A Set is a data structure which does not allow duplicate elements.
  • Stack (java.util)
    Stack is a Last-In/First-Out(LIFO) data structure which represents a stack of objects. It enables u
  • BlockingQueue (java.util.concurrent)
    A java.util.Queue that additionally supports operations that wait for the queue to become non-empty
  • Top 17 Free Sublime Text Plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyStudentsTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now