Class Reflections
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"); Setinvalid input: '<'Classinvalid input: '<'? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class); Setinvalid input: '<'Classinvalid input: '<'?>> 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:
Setinvalid input: '<'Classinvalid input: '<'? extends Module>> modules = reflections.getSubTypesOf(com.google.inject.Module.class); Setinvalid input: '<'Classinvalid input: '<'?>> singletons = reflections.getTypesAnnotatedWith(javax.inject.Singleton.class); Setinvalid input: '<'String> properties = reflections.getResources(Pattern.compile(".*\\.properties")); Setinvalid input: '<'Constructor> injectables = reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class); Setinvalid input: '<'Method> deprecateds = reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class); Setinvalid input: '<'Field> ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class); Setinvalid input: '<'Method> someMethods = reflections.getMethodsMatchParams(long.class, int.class); Setinvalid input: '<'Method> voidMethods = reflections.getMethodsReturn(void.class); Setinvalid input: '<'Method> pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(PathParam.class); Setinvalid input: '<'Method> floatToString = reflections.getConverters(Float.class, String.class); Listinvalid input: '<'String> parameterNames = reflections.getMethodsParamNames(Method.class); Setinvalid input: '<'Member> fieldUsage = reflections.getFieldUsage(Field.class); Setinvalid input: '<'Member> methodUsage = reflections.getMethodUsage(Method.class); Setinvalid input: '<'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 XmlSerializer
or JavaCodeSerializer
In order to collect pre saved metadata and avoid re-scanning, use collect(String, java.util.function.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/
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final Configuration
static org.slf4j.Logger
protected Store
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprotected
Reflections
(Object... params) a convenient constructor for Reflections, where givenObject...
parameter types can be either:String
- would add urls usingClasspathHelper.forPackage(String, ClassLoader...)
()}Class
- would add urls usingClasspathHelper.forClass(Class, ClassLoader...)
ClassLoader
- would use this classloaders in order to find urls inClasspathHelper.forPackage(String, ClassLoader...)
andClasspathHelper.forClass(Class, ClassLoader...)
Scanner
- would use given scanner, overriding the default scannersURL
- would add the given url for scanningObject
- would use each element as above use any parameter type in any order.Reflections
(String prefix, Scanner... scanners) a convenient constructor for scanning within a package prefix.Reflections
(Configuration configuration) constructs a Reflections instance and scan according to givenConfiguration
-
Method Summary
Modifier and TypeMethodDescriptionstatic Reflections
collect()
collect saved Reflection xml resources and merge it into a Reflections instancemerges saved Reflections resources from the given file, using the serializer configured in this instance's Configurationcollect
(InputStream inputStream) merges saved Reflections resources from the given input stream, using the serializer configured in this instance's Configuration
useful if you know the serialized resource location and prefer not to look it up the classpathstatic Reflections
collect
(String packagePrefix, Predicate<String> resourceNameFilter, Serializer... optionalSerializer) collect saved Reflections resources from all urls that contains the given packagePrefix and matches the given resourceNameFilter and de-serializes them using the default serializerXmlSerializer
or using the optionally supplied optionalSerializerprivate void
expandSupertypes
(Store store, String key, Class<?> type) void
expand super types after scanning, for super types that were not scanned.protected Collection
<String> getAllAnnotated
(Collection<String> annotated, Class<? extends Annotation> annotation, boolean honorInherited) get all types scanned.returns theConfiguration
object of this instancegetConstructorParamNames
(Constructor constructor) get parameter names of givenconstructor
getConstructorsAnnotatedWith
(Annotation annotation) get all constructors annotated with a given annotation, including annotation member values matchinggetConstructorsAnnotatedWith
(Class<? extends Annotation> annotation) get all constructors annotated with a given annotationgetConstructorsMatchParams
(Class<?>... types) get constructors with parameter types matching giventypes
getConstructorsWithAnyParamAnnotated
(Annotation annotation) get constructors with any parameter annotated with given annotation, including annotation member values matchinggetConstructorsWithAnyParamAnnotated
(Class<? extends Annotation> annotation) get constructors with any parameter annotated with given annotationgetConstructorUsage
(Constructor constructor) get all givenconstructors
usages in methods and constructorsgetFieldsAnnotatedWith
(Annotation annotation) get all methods annotated with a given annotation, including annotation member values matchinggetFieldsAnnotatedWith
(Class<? extends Annotation> annotation) get all fields annotated with a given annotationgetFieldUsage
(Field field) get all givenfield
usages in methods and constructorsgetMethodParamNames
(Method method) get parameter names of givenmethod
getMethodsAnnotatedWith
(Annotation annotation) get all methods annotated with a given annotation, including annotation member values matchinggetMethodsAnnotatedWith
(Class<? extends Annotation> annotation) get all methods annotated with a given annotationgetMethodsMatchParams
(Class<?>... types) get methods with parameter types matching giventypes
getMethodsReturn
(Class returnType) get methods with return type match given typegetMethodsWithAnyParamAnnotated
(Annotation annotation) get methods with any parameter annotated with given annotation, including annotation member values matchinggetMethodsWithAnyParamAnnotated
(Class<? extends Annotation> annotation) get methods with any parameter annotated with given annotationgetMethodUsage
(Method method) get all givenmethod
usages in methods and constructorsgetResources
(Predicate<String> namePredicate) get resources relative paths where simple name (key) matches given namePredicategetResources
(Pattern pattern) get resources relative paths where simple name (key) matches given regular expressiongetStore()
returns theStore
used for storing and querying the metadatagetSubTypesOf
(Class<T> type) gets all sub types in hierarchy of a given typegetTypesAnnotatedWith
(Annotation annotation) get types annotated with a given annotation, both classes and annotations, including annotation member values matchinggetTypesAnnotatedWith
(Annotation annotation, boolean honorInherited) get types annotated with a given annotation, both classes and annotations, including annotation member values matchinggetTypesAnnotatedWith
(Class<? extends Annotation> annotation) get types annotated with a given annotation, both classes and annotationsgetTypesAnnotatedWith
(Class<? extends Annotation> annotation, boolean honorInherited) get types annotated with a given annotation, both classes and annotationsprivate ClassLoader[]
loaders()
merge
(Reflections reflections) merges a Reflections instance metadata into this instanceprivate static String
producingDescription
(Store store) serialize to a given directory and filenamesave
(String filename, Serializer serializer) serialize to a given directory and filename using given serializerprotected void
scan()
protected void
-
Field Details
-
log
public static org.slf4j.Logger log -
configuration
-
store
-
-
Constructor Details
-
Reflections
constructs a Reflections instance and scan according to givenConfiguration
it is preferred to use
ConfigurationBuilder
-
Reflections
a convenient constructor for scanning within a package prefix.this actually create a
Configuration
with:
- urls that contain resources with nameprefix
- filterInputsBy where name starts with the givenprefix
- scanners set to the givenscanners
, otherwise defaults toTypeAnnotationsScanner
andSubTypesScanner
.- Parameters:
prefix
- package prefix, to be used withClasspathHelper.forPackage(String, ClassLoader...)
)}scanners
- optionally supply scanners, otherwise defaults toTypeAnnotationsScanner
andSubTypesScanner
-
Reflections
a convenient constructor for Reflections, where givenObject...
parameter types can be either:String
- would add urls usingClasspathHelper.forPackage(String, ClassLoader...)
()}Class
- would add urls usingClasspathHelper.forClass(Class, ClassLoader...)
ClassLoader
- would use this classloaders in order to find urls inClasspathHelper.forPackage(String, ClassLoader...)
andClasspathHelper.forClass(Class, ClassLoader...)
Scanner
- would use given scanner, overriding the default scannersURL
- would add the given url for scanningObject
- would use each element as above
ConfigurationBuilder
appropriately. if you prefer the usual statically typed constructor, don't use this, although it can be very useful.
for example:new Reflections("my.package", classLoader); //or new Reflections("my.package", someScanner, anotherScanner, classLoader); //or new Reflections(myUrl, myOtherUrl);
-
Reflections
protected Reflections()
-
-
Method Details
-
scan
protected void scan() -
producingDescription
-
scan
-
collect
collect saved Reflection xml resources and merge it into a Reflections instanceby default, resources are collected from all urls that contains the package META-INF/reflections and includes files matching the pattern .*-reflections.xml
-
collect
public static Reflections collect(String packagePrefix, Predicate<String> resourceNameFilter, Serializer... optionalSerializer) collect saved Reflections resources from all urls that contains the given packagePrefix and matches the given resourceNameFilter and de-serializes them using the default serializerXmlSerializer
or using the optionally supplied optionalSerializerit is preferred to use a designated resource prefix (for example META-INF/reflections but not just META-INF), so that relevant urls could be found much faster
- Parameters:
optionalSerializer
- - optionally supply one serializer instance. if not specified or null,XmlSerializer
will be used
-
collect
merges saved Reflections resources from the given input stream, using the serializer configured in this instance's Configuration
useful if you know the serialized resource location and prefer not to look it up the classpath -
collect
merges saved Reflections resources from the given file, using the serializer configured in this instance's Configurationuseful if you know the serialized resource location and prefer not to look it up the classpath
-
merge
merges a Reflections instance metadata into this instance -
expandSuperTypes
public void expandSuperTypes()expand super types after scanning, for super types that were not scanned. this is helpful in finding the transitive closure without scanning all 3rd party dependencies. it usesReflectionUtils.getSuperTypes(Class)
.for example, for classes A,B,C where A supertype of B, B supertype of C:
- if scanning C resulted in B (B->C in store), but A was not scanned (although A supertype of B) - then getSubTypes(A) will not return C
- if expanding supertypes, B will be expanded with A (A->B in store) - then getSubTypes(A) will return C
-
expandSupertypes
-
getSubTypesOf
gets all sub types in hierarchy of a given type depends on SubTypesScanner configured -
getTypesAnnotatedWith
get types annotated with a given annotation, both classes and annotationsInherited
is not honored by default.when honoring @Inherited, meta-annotation should only effect annotated super classes and its sub types
Note that this (@Inherited) meta-annotation type has no effect if the annotated type is used for anything other then a class. Also, this meta-annotation causes annotations to be inherited only from superclasses; annotations on implemented interfaces have no effect.
depends on TypeAnnotationsScanner and SubTypesScanner configured -
getTypesAnnotatedWith
public Set<Class<?>> getTypesAnnotatedWith(Class<? extends Annotation> annotation, boolean honorInherited) get types annotated with a given annotation, both classes and annotationsInherited
is honored according to given honorInherited.when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types
when not honoring @Inherited, meta annotation effects all subtypes, including annotations interfaces and classes
Note that this (@Inherited) meta-annotation type has no effect if the annotated type is used for anything other then a class. Also, this meta-annotation causes annotations to be inherited only from superclasses; annotations on implemented interfaces have no effect.
depends on TypeAnnotationsScanner and SubTypesScanner configured -
getTypesAnnotatedWith
get types annotated with a given annotation, both classes and annotations, including annotation member values matching
depends on TypeAnnotationsScanner configuredInherited
is not honored by default -
getTypesAnnotatedWith
get types annotated with a given annotation, both classes and annotations, including annotation member values matching
depends on TypeAnnotationsScanner configuredInherited
is honored according to given honorInherited -
getAllAnnotated
protected Collection<String> getAllAnnotated(Collection<String> annotated, Class<? extends Annotation> annotation, boolean honorInherited) -
getMethodsAnnotatedWith
get all methods annotated with a given annotation depends on MethodAnnotationsScanner configured -
getMethodsAnnotatedWith
get all methods annotated with a given annotation, including annotation member values matching depends on MethodAnnotationsScanner configured -
getMethodsMatchParams
get methods with parameter types matching giventypes
-
getMethodsReturn
get methods with return type match given type -
getMethodsWithAnyParamAnnotated
get methods with any parameter annotated with given annotation -
getMethodsWithAnyParamAnnotated
get methods with any parameter annotated with given annotation, including annotation member values matching -
getConstructorsAnnotatedWith
get all constructors annotated with a given annotation depends on MethodAnnotationsScanner configured -
getConstructorsAnnotatedWith
get all constructors annotated with a given annotation, including annotation member values matching depends on MethodAnnotationsScanner configured -
getConstructorsMatchParams
get constructors with parameter types matching giventypes
-
getConstructorsWithAnyParamAnnotated
public Set<Constructor> getConstructorsWithAnyParamAnnotated(Class<? extends Annotation> annotation) get constructors with any parameter annotated with given annotation -
getConstructorsWithAnyParamAnnotated
get constructors with any parameter annotated with given annotation, including annotation member values matching -
getFieldsAnnotatedWith
get all fields annotated with a given annotation depends on FieldAnnotationsScanner configured -
getFieldsAnnotatedWith
get all methods annotated with a given annotation, including annotation member values matching depends on FieldAnnotationsScanner configured -
getResources
get resources relative paths where simple name (key) matches given namePredicatedepends on ResourcesScanner configured
-
getResources
get resources relative paths where simple name (key) matches given regular expressiondepends on ResourcesScanner configured
Set
xmls = reflections.getResources(".*\\.xml"); -
getMethodParamNames
get parameter names of givenmethod
depends on MethodParameterNamesScanner configured
-
getConstructorParamNames
get parameter names of givenconstructor
depends on MethodParameterNamesScanner configured
-
getFieldUsage
get all givenfield
usages in methods and constructorsdepends on MemberUsageScanner configured
-
getMethodUsage
get all givenmethod
usages in methods and constructorsdepends on MemberUsageScanner configured
-
getConstructorUsage
get all givenconstructors
usages in methods and constructorsdepends on MemberUsageScanner configured
-
getAllTypes
get all types scanned. this is effectively similar to getting all subtypes of Object.depends on SubTypesScanner configured with
SubTypesScanner(false)
, otherwiseReflectionsException
is thrownnote using this might be a bad practice. it is better to get types matching some criteria, such as
getSubTypesOf(Class)
orgetTypesAnnotatedWith(Class)
- Returns:
- Set of String, and not of Class, in order to avoid definition of all types in PermGen
-
getStore
returns theStore
used for storing and querying the metadata -
getConfiguration
returns theConfiguration
object of this instance -
save
serialize to a given directory and filename* it is preferred to specify a designated directory (for example META-INF/reflections), so that it could be found later much faster using the load method
see the documentation for the save method on the configured
Serializer
-
save
serialize to a given directory and filename using given serializer* it is preferred to specify a designated directory (for example META-INF/reflections), so that it could be found later much faster using the load method
-
loaders
-