Skip to content

Commit

Permalink
Reduce scanning verbosity #1
Browse files Browse the repository at this point in the history
- Added timing information
- Verbosity reduced for metadata scanning
- Added "reflections17.verbose" environment variable detection for
  convenient verbosity tuning in cloud deployments
  • Loading branch information
mhickson committed Mar 16, 2024
1 parent d8a1243 commit d1a2c55
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 79 deletions.
25 changes: 0 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,3 @@
This fork is changed to use java8 instead of guava.

```xml
<dependency>
<groupId>net.oneandone.reflections8</groupId>
<artifactId>reflections8</artifactId>
<version>0.11.5</version>
</dependency>
```

To avoid mixup of classes between "pre java8"-reflections and reflections8 all is moved from org.reflections to org.reflections8
[![Build Status](https://travis-ci.org/aschoerk/reflections8.svg?branch=master)](https://travis-ci.org/aschoerk/reflections8)



----

## Java runtime metadata analysis, in the spirit of [Scannotations](http://bill.burkecentral.com/2008/01/14/scanning-java-annotations-at-runtime/)

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.
Expand All @@ -28,14 +11,6 @@ Using Reflections you can query your metadata such as:
[![Build Status](https://travis-ci.org/ronmamo/reflections.svg?branch=master)](https://travis-ci.org/ronmamo/reflections)

### Intro
Add Reflections to your project. for maven projects just add this dependency:
```xml
<dependency>
<groupId>net.oneandone.reflections8</groupId>
<artifactId>reflections8</artifactId>
<version>0.11.5</version>
</dependency>
```

A typical use of Reflections would be:
```java
Expand Down
24 changes: 10 additions & 14 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>net.oneandone.reflections8</groupId>
<artifactId>reflections8</artifactId>
<version>0.11.6</version>
<groupId>org.reflections17</groupId>
<artifactId>reflections17</artifactId>
<version>1.0.2</version>

<name>Reflections8</name>
<description>Reflections8 - a Java runtime metadata analysis without guava on Java 8</description>
<url>http://github.com/aschoerk/reflections8</url>
<name>Reflections17</name>
<description>Reflections17 - a Java runtime metadata analysis component</description>

<licenses>
<license>
Expand All @@ -21,19 +20,17 @@
</licenses>

<scm>
<url>https://github.com/aschoerk/reflections8</url>
<connection>scm:git:ssh://git@github.com/aschoerk/reflections8.git</connection>
<developerConnection>scm:git:ssh://git@github.com/aschoerk/reflections8.git</developerConnection>
<tag>v0.11.6</tag>
<url>https://github.com/martinhickson/reflections8</url>
<connection>git@github.com:martinhickson/reflections8.git</connection>
<developerConnection>git@github.com:martinhickson/reflections8.git</developerConnection>
<tag>v1.0.2</tag>
</scm>


<issueManagement>
<url>https://github.com/aschoerk/reflections8/issues</url>
<url>https://github.com/martinhickson/reflections8/issues</url>
<system>GitHub Issues</system>
</issueManagement>


<developers>
<developer>
<name>Andreas Schörk</name>
Expand Down Expand Up @@ -64,7 +61,6 @@
</properties>

<dependencies>

<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
Expand Down
91 changes: 55 additions & 36 deletions src/main/java/org/reflections8/ReflectionUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import org.reflections8.util.AlwaysTruePredicate;
import org.reflections8.util.ClasspathHelper;
import org.slf4j.Logger;

/** convenient java reflection helper methods
* <p>
Expand All @@ -38,7 +39,7 @@
* <li>{@link #getAllMethods(Class, Predicate...)}
* <li>{@link #getAllConstructors(Class,Predicate...)}
* </ul>
* <p>and predicates included here all starts with "with", such as
* <p>and predicates included here all starts with "with", such as
* <ul>
* <li>{@link #withAnnotation(java.lang.annotation.Annotation)}
* <li>{@link #withModifier(int)}
Expand All @@ -51,28 +52,42 @@
* <li>{@link #withReturnType(Class)}
* <li>{@link #withType(Class)}
* <li>{@link #withTypeAssignableTo}
* </ul>
* </ul>
*
* <p><br>
* for example, getting all getters would be:
* <pre>
* Set&lt;Method&gt; getters = getAllMethods(someClasses,
* Predicates.and(
* withModifier(Modifier.PUBLIC),
* withPrefix("get"),
* withModifier(Modifier.PUBLIC),
* withPrefix("get"),
* withParametersCount(0)));
* </pre>
* */
@SuppressWarnings("unchecked")
public abstract class ReflectionUtils {

private static final String SEMICOLON = ";";

private static final String L = "L";

private static final String EMPTY_STRING = "";

private static final String CLOSE_SQUARE_BRACKET = "]";

private static final String OPEN_SQUARE_BRACKET = "[";

private static final String TYPE_UNAVAILABLE_SHORT = "Type: %s unavailable";

private static final String TYPE_UNAVAILABLE = "Type: %s unavailable from any class loader";

/** would include {@code Object.class} when {@link #getAllSuperTypes(Class, Predicate[])}. default is false. */
public static final boolean includeObject = false;

/** get all super types of given {@code type}, including, optionally filtered by {@code predicates}
* <p> include {@code Object.class} if {@link #includeObject} is true */
public static Set<Class<?>> getAllSuperTypes(final Class<?> type, Predicate<? super Class<?>>... predicates) {
Set<Class<?>> result = new LinkedHashSet();
Set<Class<?>> result = new LinkedHashSet<Class<?>>();
if (type != null && (includeObject || !type.equals(Object.class))) {
result.add(type);
for (Class<?> supertype : getSuperTypes(type)) {
Expand All @@ -94,7 +109,7 @@ public static Set<Class<?>> getSuperTypes(Class<?> type) {

/** get all methods of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */
public static Set<Method> getAllMethods(final Class<?> type, Predicate<? super Method>... predicates) {
Set<Method> result = new HashSet();
Set<Method> result = new HashSet<Method>();
for (Class<?> t : getAllSuperTypes(type)) {
result.addAll(getMethods(t, predicates));
}
Expand All @@ -108,7 +123,7 @@ public static Set<Method> getMethods(Class<?> t, Predicate<? super Method>... pr

/** get all constructors of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */
public static Set<Constructor> getAllConstructors(final Class<?> type, Predicate<? super Constructor>... predicates) {
Set<Constructor> result = new HashSet();
Set<Constructor> result = new HashSet<Constructor>();
for (Class<?> t : getAllSuperTypes(type)) {
result.addAll(getConstructors(t, predicates));
}
Expand All @@ -122,7 +137,7 @@ public static Set<Constructor> getConstructors(Class<?> t, Predicate<? super Con

/** get all fields of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */
public static Set<Field> getAllFields(final Class<?> type, Predicate<? super Field>... predicates) {
Set<Field> result = new HashSet();
Set<Field> result = new HashSet<Field>();
for (Class<?> t : getAllSuperTypes(type)) result.addAll(getFields(t, predicates));
return result;
}
Expand All @@ -134,7 +149,7 @@ public static Set<Field> getFields(Class<?> type, Predicate<? super Field>... pr

/** get all annotations of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */
public static <T extends AnnotatedElement> Set<Annotation> getAllAnnotations(T type, Predicate<Annotation>... predicates) {
Set<Annotation> result = new HashSet();
Set<Annotation> result = new HashSet<Annotation>();
if (type instanceof Class) {
for (Class<?> t : getAllSuperTypes((Class<?>) type)) {
result.addAll(getAnnotations(t, predicates));
Expand Down Expand Up @@ -370,56 +385,60 @@ public static Class<?> forName(String typeName, ClassLoader ... classLoaders) {
} else {
return forName(typeName, Optional.of(classLoaders));
}

}


//
/** tries to resolve a java type name to a Class
* <p>if optional {@link ClassLoader}s are not specified, then both {@link org.reflections8.util.ClasspathHelper#contextClassLoader()} and {@link org.reflections8.util.ClasspathHelper#staticClassLoader()} are used
* */
/**
* Tries to resolve a java type name to a Class
* <p>if optional {@link ClassLoader}s are not specified, then both {@link org.reflections8.util.ClasspathHelper#contextClassLoader()}
* and {@link org.reflections8.util.ClasspathHelper#staticClassLoader()} are used
*/
public static Class<?> forName(String typeName, Optional<ClassLoader[]> classLoaders) {
if (getPrimitiveNames().contains(typeName)) {
return getPrimitiveTypes().get(getPrimitiveNames().indexOf(typeName));
} else {
String type;
if (typeName.contains("[")) {
int i = typeName.indexOf("[");
if (typeName.contains(OPEN_SQUARE_BRACKET)) {
int i = typeName.indexOf(OPEN_SQUARE_BRACKET);
type = typeName.substring(0, i);
String array = typeName.substring(i).replace("]", "");

String array = typeName.substring(i).replace(CLOSE_SQUARE_BRACKET, EMPTY_STRING);
if (getPrimitiveNames().contains(type)) {
type = getPrimitiveDescriptors().get(getPrimitiveNames().indexOf(type));
} else {
type = "L" + type + ";";
type = L + type + SEMICOLON;
}

type = array + type;
} else {
type = typeName;
}

List<ReflectionsException> reflectionsExceptions = new ArrayList();
List<ReflectionsException> reflectionsExceptions = new ArrayList<ReflectionsException>();
for (ClassLoader classLoader : ClasspathHelper.classLoaders(classLoaders).get()) {
if (type.contains("[")) {
try { return Class.forName(type, false, classLoader); }
catch (Throwable e) {
reflectionsExceptions.add(new ReflectionsException("could not get type for name " + typeName, e));
if (type.contains(OPEN_SQUARE_BRACKET)) {
try {
return Class.forName(type, false, classLoader);
} catch (Throwable e) {
reflectionsExceptions.add(new ReflectionsException(String.format(TYPE_UNAVAILABLE_SHORT, typeName), e));
}
}
try { return classLoader.loadClass(type); }
catch (Throwable e) {
reflectionsExceptions.add(new ReflectionsException("could not get type for name " + typeName, e));
try {
return classLoader.loadClass(type);
} catch (Throwable e) {
reflectionsExceptions.add(new ReflectionsException(String.format(TYPE_UNAVAILABLE_SHORT, typeName), e));
}
}

if (Reflections.log.isPresent()) {
Logger logger = Reflections.log.get();
for (ReflectionsException reflectionsException : reflectionsExceptions) {
Reflections.log.get().warn("could not get type for name " + typeName + " from any class loader",
reflectionsException);
boolean traceEnabled = logger.isTraceEnabled();
if (Reflections.REFLECTIONS_VERBOSE_SCANNING || traceEnabled) {
String message = String.format(TYPE_UNAVAILABLE, typeName);
if (traceEnabled) {
logger.trace(message, reflectionsException);
} else {
logger.warn(message, reflectionsException);
}
}
}
}

return null;
}
}
Expand Down Expand Up @@ -451,7 +470,7 @@ private static Class[] parameterTypes(Member member) {
}

private static Set<Annotation> parameterAnnotations(Member member) {
Set<Annotation> result = new HashSet();
Set<Annotation> result = new HashSet<Annotation>();
Annotation[][] annotations =
member instanceof Method ? ((Method) member).getParameterAnnotations() :
member instanceof Constructor ? ((Constructor) member).getParameterAnnotations() : null;
Expand All @@ -462,7 +481,7 @@ private static Set<Annotation> parameterAnnotations(Member member) {
}

private static Set<Class<? extends Annotation>> annotationTypes(Iterable<Annotation> annotations) {
Set<Class<? extends Annotation>> result = new HashSet();
Set<Class<? extends Annotation>> result = new HashSet<Class<? extends Annotation>>();
for (Annotation annotation : annotations) result.add(annotation.annotationType());
return result;
}
Expand Down
33 changes: 29 additions & 4 deletions src/main/java/org/reflections8/Reflections.java
Original file line number Diff line number Diff line change
Expand Up @@ -132,32 +132,57 @@
* <p><p><p>For Javadoc, source code, and more information about Reflections Library, see http://github.com/ronmamo/reflections/
*/
public class Reflections {

/*
* Provide for convenient verbosity tuning in cloud deployments via the
* "reflections17.verbose.timing" and "reflection17.verbose.scanning"
* environment variables:
*/
private static final String VERBOSE_TIMING_PROPERTY = "reflections17.verbose.timing";

private static final String VERBOSE_SCANNING_PROPERTY = "reflections17.verbose.scanning";

static final boolean REFLECTIONS_VERBOSE_TIMING = Boolean.getBoolean(VERBOSE_TIMING_PROPERTY)
|| "true".equals(System.getenv(VERBOSE_TIMING_PROPERTY));

static final boolean REFLECTIONS_VERBOSE_SCANNING = Boolean.getBoolean(VERBOSE_SCANNING_PROPERTY)
|| "true".equals(System.getenv(VERBOSE_SCANNING_PROPERTY));

private static final String TIMING_INFO = "Reflections initialized in {} ms";

public static final Optional<Logger> log = findLogger(Reflections.class);

protected final transient Configuration configuration;

protected Store store;

/**
* constructs a Reflections instance and scan according to given {@link org.reflections8.Configuration}
* <p>it is preferred to use {@link org.reflections8.util.ConfigurationBuilder}
*/
public Reflections(final Configuration configuration) {
long start = System.currentTimeMillis();
this.configuration = configuration;
store = new Store(configuration);

if (configuration.getScanners() != null && !configuration.getScanners().isEmpty()) {
//inject to scanners
for (Scanner scanner : configuration.getScanners()) {
scanner.setConfiguration(configuration);
scanner.setStore(store.getOrCreate(index(scanner.getClass())));
}

scan();

if (configuration.shouldExpandSuperTypes()) {
expandSuperTypes();
}
}
Logger logger = log.get();
if (REFLECTIONS_VERBOSE_TIMING || logger.isTraceEnabled()) {
long end = System.currentTimeMillis();
if (REFLECTIONS_VERBOSE_TIMING) {
logger.warn(TIMING_INFO, end - start);
} else {
logger.trace(TIMING_INFO, end - start);
}
}
}

/**
Expand Down

0 comments on commit d1a2c55

Please sign in to comment.