From 937c8f359debb21e7babe92300a8fcc64ff3c6d8 Mon Sep 17 00:00:00 2001 From: ronma Date: Mon, 6 Jan 2020 09:47:43 +0700 Subject: [PATCH 1/4] migrate to java 8. removed guava and migrated to streams api. simplified store. cleanups. --- .travis.yml | 11 + pom.xml | 28 +- .../java/org/reflections/Configuration.java | 5 +- .../java/org/reflections/ReflectionUtils.java | 210 ++++-------- .../java/org/reflections/Reflections.java | 227 +++++++------ src/main/java/org/reflections/Store.java | 146 ++++++--- .../adapters/JavaReflectionAdapter.java | 24 +- .../adapters/JavassistAdapter.java | 41 ++- .../reflections/scanners/AbstractScanner.java | 32 +- .../scanners/FieldAnnotationsScanner.java | 6 +- .../scanners/MemberUsageScanner.java | 39 ++- .../scanners/MethodAnnotationsScanner.java | 6 +- .../scanners/MethodParameterNamesScanner.java | 17 +- .../scanners/MethodParameterScanner.java | 9 +- .../scanners/ResourcesScanner.java | 7 +- .../org/reflections/scanners/Scanner.java | 11 +- .../reflections/scanners/SubTypesScanner.java | 7 +- .../scanners/TypeAnnotationsScanner.java | 6 +- .../scanners/TypeElementsScanner.java | 16 +- .../reflections/scanners/TypesScanner.java | 23 -- .../serializers/JavaCodeSerializer.java | 63 ++-- .../serializers/JsonSerializer.java | 44 +-- .../serializers/XmlSerializer.java | 12 +- .../org/reflections/util/ClasspathHelper.java | 23 +- .../util/ConfigurationBuilder.java | 79 ++--- .../org/reflections/util/FilterBuilder.java | 38 +-- src/main/java/org/reflections/util/Utils.java | 52 ++- .../java/org/reflections/vfs/JarInputDir.java | 59 ++-- .../java/org/reflections/vfs/SystemDir.java | 46 +-- .../java/org/reflections/vfs/UrlTypeVFS.java | 21 +- src/main/java/org/reflections/vfs/Vfs.java | 73 ++--- src/main/java/org/reflections/vfs/ZipDir.java | 27 +- .../org/reflections/ClasspathHelperTest.java | 1 - .../org/reflections/FilterBuilderTest.java | 128 ++++---- .../reflections/JavaCodeSerializerTest.java | 12 +- .../org/reflections/MyTestModelStore.java | 14 +- .../org/reflections/ReflectionUtilsTest.java | 20 +- .../reflections/ReflectionsCollectTest.java | 18 +- .../ReflectionsExpandSupertypesTest.java | 2 +- .../reflections/ReflectionsParallelTest.java | 17 +- .../java/org/reflections/ReflectionsTest.java | 58 ++-- .../ReflectionsThreadSafenessTest.java | 15 +- src/test/java/org/reflections/VfsTest.java | 308 +++++------------- 43 files changed, 877 insertions(+), 1124 deletions(-) delete mode 100644 src/main/java/org/reflections/scanners/TypesScanner.java diff --git a/.travis.yml b/.travis.yml index dff5f3a5..521e981d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1 +1,12 @@ language: java + +jdk: + - oraclejdk8 + - oraclejdk11 + - openjdk8 + - openjdk11 + +addons: + apt: + packages: + - oracle-java8-installer \ No newline at end of file diff --git a/pom.xml b/pom.xml index 88c90e30..5f237c73 100644 --- a/pom.xml +++ b/pom.xml @@ -52,19 +52,12 @@ - 20.0 - 3.21.0-GA - 1.7 + 3.26.0-GA + 1.8 -Xdoclint:none - - com.google.guava - guava - ${guava.version} - - org.javassist javassist @@ -76,21 +69,21 @@ org.slf4j slf4j-api - 1.7.24 + 1.7.30 true - dom4j + org.dom4j dom4j - 1.6.1 + 2.1.1 true com.google.code.gson gson - 2.8.0 + 2.8.6 true @@ -110,17 +103,10 @@ true - - com.google.code.findbugs - jsr305 - 3.0.1 - provided - - junit junit - 4.12 + 4.13 test diff --git a/src/main/java/org/reflections/Configuration.java b/src/main/java/org/reflections/Configuration.java index 5da07c87..18115144 100644 --- a/src/main/java/org/reflections/Configuration.java +++ b/src/main/java/org/reflections/Configuration.java @@ -1,14 +1,13 @@ package org.reflections; -import com.google.common.base.Predicate; import org.reflections.adapters.MetadataAdapter; import org.reflections.scanners.Scanner; import org.reflections.serializers.Serializer; -import javax.annotation.Nullable; import java.net.URL; import java.util.Set; import java.util.concurrent.ExecutorService; +import java.util.function.Predicate; /** * Configuration is used to create a configured instance of {@link Reflections} @@ -26,7 +25,6 @@ public interface Configuration { MetadataAdapter getMetadataAdapter(); /** get the fully qualified name filter used to filter types to be scanned */ - @Nullable Predicate getInputsFilter(); /** executor service used to scan files. if null, scanning is done in a simple for loop */ @@ -36,7 +34,6 @@ public interface Configuration { Serializer getSerializer(); /** get class loaders, might be used for resolving methods/fields */ - @Nullable ClassLoader[] getClassLoaders(); /** if true (default), expand super types after scanning, for super types that were not scanned. diff --git a/src/main/java/org/reflections/ReflectionUtils.java b/src/main/java/org/reflections/ReflectionUtils.java index 699ef706..aa178136 100644 --- a/src/main/java/org/reflections/ReflectionUtils.java +++ b/src/main/java/org/reflections/ReflectionUtils.java @@ -1,32 +1,38 @@ package org.reflections; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import org.reflections.util.ClasspathHelper; -import javax.annotation.Nullable; import java.lang.annotation.Annotation; -import java.lang.reflect.*; -import java.util.*; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; import java.util.regex.Pattern; -import static org.reflections.util.Utils.isEmpty; +import static org.reflections.util.Utils.filter; /** convenient java reflection helper methods *

- * 1. some helper methods to get type by name: {@link #forName(String, ClassLoader...)} and {@link #forNames(Iterable, ClassLoader...)} + * 1. some helper methods to get type by name: {@link #forName(String, ClassLoader...)} and {@link #forNames(Collection, ClassLoader...)} )} *

* 2. some helper methods to get all types/methods/fields/constructors/properties matching some predicates, generally: *

 Set<?> result = getAllXXX(type/s, withYYY) 
*

where get methods are: *

    - *
  • {@link #getAllSuperTypes(Class, com.google.common.base.Predicate...)} - *
  • {@link #getAllFields(Class, com.google.common.base.Predicate...)} - *
  • {@link #getAllMethods(Class, com.google.common.base.Predicate...)} - *
  • {@link #getAllConstructors(Class, com.google.common.base.Predicate...)} + *
  • {@link #getAllSuperTypes(Class, java.util.function.Predicate...)} + *
  • {@link #getAllFields(Class, java.util.function.Predicate...)} + *
  • {@link #getAllMethods(Class, java.util.function.Predicate...)} + *
  • {@link #getAllConstructors(Class, java.util.function.Predicate...)} *
*

and predicates included here all starts with "with", such as *

    @@ -56,13 +62,13 @@ @SuppressWarnings("unchecked") public abstract class ReflectionUtils { - /** would include {@code Object.class} when {@link #getAllSuperTypes(Class, com.google.common.base.Predicate[])}. default is false. */ + /** would include {@code Object.class} when {@link #getAllSuperTypes(Class, java.util.function.Predicate[])}. default is false. */ public static boolean includeObject = false; /** get all super types of given {@code type}, including, optionally filtered by {@code predicates} *

    include {@code Object.class} if {@link #includeObject} is true */ public static Set> getAllSuperTypes(final Class type, Predicate>... predicates) { - Set> result = Sets.newLinkedHashSet(); + Set> result = new LinkedHashSet<>(); if (type != null && (includeObject || !type.equals(Object.class))) { result.add(type); for (Class supertype : getSuperTypes(type)) { @@ -84,7 +90,7 @@ public static Set> getSuperTypes(Class type) { /** get all methods of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */ public static Set getAllMethods(final Class type, Predicate... predicates) { - Set result = Sets.newHashSet(); + Set result = new HashSet<>(); for (Class t : getAllSuperTypes(type)) { result.addAll(getMethods(t, predicates)); } @@ -98,7 +104,7 @@ public static Set getMethods(Class t, Predicate... pr /** get all constructors of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */ public static Set getAllConstructors(final Class type, Predicate... predicates) { - Set result = Sets.newHashSet(); + Set result = new HashSet<>(); for (Class t : getAllSuperTypes(type)) { result.addAll(getConstructors(t, predicates)); } @@ -107,12 +113,12 @@ public static Set getAllConstructors(final Class type, Predicate /** get constructors of given {@code type}, optionally filtered by {@code predicates} */ public static Set getConstructors(Class t, Predicate... predicates) { - return ReflectionUtils.filter(t.getDeclaredConstructors(), predicates); //explicit needed only for jdk1.5 + return filter(t.getDeclaredConstructors(), predicates); } /** get all fields of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */ public static Set getAllFields(final Class type, Predicate... predicates) { - Set result = Sets.newHashSet(); + Set result = new HashSet<>(); for (Class t : getAllSuperTypes(type)) result.addAll(getFields(t, predicates)); return result; } @@ -124,7 +130,7 @@ public static Set getFields(Class type, Predicate... pr /** get all annotations of given {@code type}, up the super class hierarchy, optionally filtered by {@code predicates} */ public static Set getAllAnnotations(T type, Predicate... predicates) { - Set result = Sets.newHashSet(); + Set result = new HashSet<>(); if (type instanceof Class) { for (Class t : getAllSuperTypes((Class) type)) { result.addAll(getAnnotations(t, predicates)); @@ -142,26 +148,18 @@ public static Set getAnnotations(T type /** filter all given {@code elements} with {@code predicates}, if given */ public static Set getAll(final Set elements, Predicate... predicates) { - return isEmpty(predicates) ? elements : Sets.newHashSet(Iterables.filter(elements, Predicates.and(predicates))); + return filter(elements, predicates); } //predicates /** where member name equals given {@code name} */ public static Predicate withName(final String name) { - return new Predicate() { - public boolean apply(@Nullable T input) { - return input != null && input.getName().equals(name); - } - }; + return input -> input != null && input.getName().equals(name); } /** where member name startsWith given {@code prefix} */ public static Predicate withPrefix(final String prefix) { - return new Predicate() { - public boolean apply(@Nullable T input) { - return input != null && input.getName().startsWith(prefix); - } - }; + return input -> input != null && input.getName().startsWith(prefix); } /** where member's {@code toString} matches given {@code regex} @@ -171,154 +169,88 @@ public boolean apply(@Nullable T input) { * * */ public static Predicate withPattern(final String regex) { - return new Predicate() { - public boolean apply(@Nullable T input) { - return Pattern.matches(regex, input.toString()); - } - }; + return input -> Pattern.matches(regex, input.toString()); } /** where element is annotated with given {@code annotation} */ public static Predicate withAnnotation(final Class annotation) { - return new Predicate() { - public boolean apply(@Nullable T input) { - return input != null && input.isAnnotationPresent(annotation); - } - }; + return input -> input != null && input.isAnnotationPresent(annotation); } /** where element is annotated with given {@code annotations} */ public static Predicate withAnnotations(final Class... annotations) { - return new Predicate() { - public boolean apply(@Nullable T input) { - return input != null && Arrays.equals(annotations, annotationTypes(input.getAnnotations())); - } - }; + return input -> input != null && Arrays.equals(annotations, annotationTypes(input.getAnnotations())); } /** where element is annotated with given {@code annotation}, including member matching */ public static Predicate withAnnotation(final Annotation annotation) { - return new Predicate() { - public boolean apply(@Nullable T input) { - return input != null && input.isAnnotationPresent(annotation.annotationType()) && - areAnnotationMembersMatching(input.getAnnotation(annotation.annotationType()), annotation); - } - }; + return input -> input != null && input.isAnnotationPresent(annotation.annotationType()) && + areAnnotationMembersMatching(input.getAnnotation(annotation.annotationType()), annotation); } /** where element is annotated with given {@code annotations}, including member matching */ public static Predicate withAnnotations(final Annotation... annotations) { - return new Predicate() { - public boolean apply(@Nullable T input) { - if (input != null) { - Annotation[] inputAnnotations = input.getAnnotations(); - if (inputAnnotations.length == annotations.length) { - for (int i = 0; i < inputAnnotations.length; i++) { - if (!areAnnotationMembersMatching(inputAnnotations[i], annotations[i])) return false; - } + return input -> { + if (input != null) { + Annotation[] inputAnnotations = input.getAnnotations(); + if (inputAnnotations.length == annotations.length) { + for (int i = 0; i < inputAnnotations.length; i++) { + if (!areAnnotationMembersMatching(inputAnnotations[i], annotations[i])) return false; } } - return true; } + return true; }; } /** when method/constructor parameter types equals given {@code types} */ public static Predicate withParameters(final Class... types) { - return new Predicate() { - public boolean apply(@Nullable Member input) { - return Arrays.equals(parameterTypes(input), types); - } - }; + return input -> Arrays.equals(parameterTypes(input), types); } /** when member parameter types assignable to given {@code types} */ public static Predicate withParametersAssignableTo(final Class... types) { - return new Predicate() { - public boolean apply(@Nullable Member input) { - return isAssignable(types, parameterTypes(input)); - } - }; + return input -> isAssignable(types, parameterTypes(input)); } /** when method/constructor parameter types assignable from given {@code types} */ public static Predicate withParametersAssignableFrom(final Class... types) { - return new Predicate() { - public boolean apply(@Nullable Member input) { - return isAssignable(parameterTypes(input), types); - } - }; + return input -> isAssignable(parameterTypes(input), types); } /** when method/constructor parameters count equal given {@code count} */ public static Predicate withParametersCount(final int count) { - return new Predicate() { - public boolean apply(@Nullable Member input) { - return input != null && parameterTypes(input).length == count; - } - }; + return input -> input != null && parameterTypes(input).length == count; } /** when method/constructor has any parameter with an annotation matches given {@code annotations} */ public static Predicate withAnyParameterAnnotation(final Class annotationClass) { - return new Predicate() { - public boolean apply(@Nullable Member input) { - return input != null && Iterables.any(annotationTypes(parameterAnnotations(input)), new Predicate>() { - public boolean apply(@Nullable Class input) { - return input.equals(annotationClass); - } - }); - } - }; + return input -> input != null && annotationTypes(parameterAnnotations(input)).stream().anyMatch(input1 -> input1.equals(annotationClass)); } /** when method/constructor has any parameter with an annotation matches given {@code annotations}, including member matching */ public static Predicate withAnyParameterAnnotation(final Annotation annotation) { - return new Predicate() { - public boolean apply(@Nullable Member input) { - return input != null && Iterables.any(parameterAnnotations(input), new Predicate() { - public boolean apply(@Nullable Annotation input) { - return areAnnotationMembersMatching(annotation, input); - } - }); - } - }; + return input -> input != null && parameterAnnotations(input).stream().anyMatch(input1 -> areAnnotationMembersMatching(annotation, input1)); } /** when field type equal given {@code type} */ public static Predicate withType(final Class type) { - return new Predicate() { - public boolean apply(@Nullable Field input) { - return input != null && input.getType().equals(type); - } - }; + return input -> input != null && input.getType().equals(type); } /** when field type assignable to given {@code type} */ public static Predicate withTypeAssignableTo(final Class type) { - return new Predicate() { - public boolean apply(@Nullable Field input) { - return input != null && type.isAssignableFrom(input.getType()); - } - }; + return input -> input != null && type.isAssignableFrom(input.getType()); } /** when method return type equal given {@code type} */ public static Predicate withReturnType(final Class type) { - return new Predicate() { - public boolean apply(@Nullable Method input) { - return input != null && input.getReturnType().equals(type); - } - }; + return input -> input != null && input.getReturnType().equals(type); } /** when method return type assignable from given {@code type} */ public static Predicate withReturnTypeAssignableTo(final Class type) { - return new Predicate() { - public boolean apply(@Nullable Method input) { - return input != null && type.isAssignableFrom(input.getReturnType()); - } - }; + return input -> input != null && type.isAssignableFrom(input.getReturnType()); } /** when member modifier matches given {@code mod} @@ -328,11 +260,7 @@ public boolean apply(@Nullable Method input) { * */ public static Predicate withModifier(final int mod) { - return new Predicate() { - public boolean apply(@Nullable T input) { - return input != null && (input.getModifiers() & mod) != 0; - } - }; + return input -> input != null && (input.getModifiers() & mod) != 0; } /** when class modifier matches given {@code mod} @@ -342,11 +270,7 @@ public boolean apply(@Nullable T input) { * */ public static Predicate> withClassModifier(final int mod) { - return new Predicate>() { - public boolean apply(@Nullable Class input) { - return input != null && (input.getModifiers() & mod) != 0; - } - }; + return input -> input != null && (input.getModifiers() & mod) != 0; } // @@ -374,7 +298,7 @@ public static Class forName(String typeName, ClassLoader... classLoaders) { type = typeName; } - List reflectionsExceptions = Lists.newArrayList(); + List reflectionsExceptions = new ArrayList<>(); for (ClassLoader classLoader : ClasspathHelper.classLoaders(classLoaders)) { if (type.contains("[")) { try { return Class.forName(type, false, classLoader); } @@ -400,8 +324,8 @@ public static Class forName(String typeName, ClassLoader... classLoaders) { } /** try to resolve all given string representation of types to a list of java types */ - public static List> forNames(final Iterable classes, ClassLoader... classLoaders) { - List> result = new ArrayList>(); + public static Set> forNames(final Collection classes, ClassLoader... classLoaders) { + Set> result = new LinkedHashSet<>(); for (String className : classes) { Class type = forName(className, classLoaders); if (type != null) { @@ -418,7 +342,7 @@ private static Class[] parameterTypes(Member member) { } private static Set parameterAnnotations(Member member) { - Set result = Sets.newHashSet(); + Set result = new HashSet<>(); Annotation[][] annotations = member instanceof Method ? ((Method) member).getParameterAnnotations() : member instanceof Constructor ? ((Constructor) member).getParameterAnnotations() : null; @@ -427,7 +351,7 @@ private static Set parameterAnnotations(Member member) { } private static Set> annotationTypes(Iterable annotations) { - Set> result = Sets.newHashSet(); + Set> result = new HashSet<>(); for (Annotation annotation : annotations) result.add(annotation.annotationType()); return result; } @@ -445,9 +369,9 @@ private static Class[] annotationTypes(Annotation[] annota private static void initPrimitives() { if (primitiveNames == null) { - primitiveNames = Lists.newArrayList("boolean", "char", "byte", "short", "int", "long", "float", "double", "void"); - primitiveTypes = Lists.newArrayList(boolean.class, char.class, byte.class, short.class, int.class, long.class, float.class, double.class, void.class); - primitiveDescriptors = Lists.newArrayList("Z", "C", "B", "S", "I", "J", "F", "D", "V"); + primitiveNames = Arrays.asList("boolean", "char", "byte", "short", "int", "long", "float", "double", "void"); + primitiveTypes = Arrays.asList(boolean.class, char.class, byte.class, short.class, int.class, long.class, float.class, double.class, void.class); + primitiveDescriptors = Arrays.asList("Z", "C", "B", "S", "I", "J", "F", "D", "V"); } } @@ -456,16 +380,6 @@ private static void initPrimitives() { private static List getPrimitiveDescriptors() { initPrimitives(); return primitiveDescriptors; } // - static Set filter(final T[] elements, Predicate... predicates) { - return isEmpty(predicates) ? Sets.newHashSet(elements) : - Sets.newHashSet(Iterables.filter(Arrays.asList(elements), Predicates.and(predicates))); - } - - static Set filter(final Iterable elements, Predicate... predicates) { - return isEmpty(predicates) ? Sets.newHashSet(elements) : - Sets.newHashSet(Iterables.filter(elements, Predicates.and(predicates))); - } - private static boolean areAnnotationMembersMatching(Annotation annotation1, Annotation annotation2) { if (annotation2 != null && annotation1.annotationType() == annotation2.annotationType()) { for (Method method : annotation1.annotationType().getDeclaredMethods()) { diff --git a/src/main/java/org/reflections/Reflections.java b/src/main/java/org/reflections/Reflections.java index e22cad76..627f6a6f 100644 --- a/src/main/java/org/reflections/Reflections.java +++ b/src/main/java/org/reflections/Reflections.java @@ -1,18 +1,28 @@ package org.reflections; -import com.google.common.base.Joiner; -import com.google.common.base.Predicate; -import com.google.common.collect.*; -import org.reflections.scanners.*; +import org.reflections.scanners.FieldAnnotationsScanner; +import org.reflections.scanners.MemberUsageScanner; +import org.reflections.scanners.MethodAnnotationsScanner; +import org.reflections.scanners.MethodParameterNamesScanner; +import org.reflections.scanners.MethodParameterScanner; +import org.reflections.scanners.ResourcesScanner; import org.reflections.scanners.Scanner; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.serializers.Serializer; import org.reflections.serializers.XmlSerializer; -import org.reflections.util.*; +import org.reflections.util.ClasspathHelper; +import org.reflections.util.ConfigurationBuilder; +import org.reflections.util.FilterBuilder; +import org.reflections.util.Utils; import org.reflections.vfs.Vfs; import org.slf4j.Logger; -import javax.annotation.Nullable; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.annotation.Inherited; import java.lang.reflect.Constructor; @@ -20,15 +30,20 @@ import java.lang.reflect.Member; import java.lang.reflect.Method; import java.net.URL; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; +import java.util.function.Predicate; import java.util.regex.Pattern; +import java.util.stream.Collectors; -import static com.google.common.base.Predicates.in; -import static com.google.common.base.Predicates.not; -import static com.google.common.collect.Iterables.concat; import static java.lang.String.format; import static org.reflections.ReflectionUtils.*; import static org.reflections.util.Utils.*; @@ -92,7 +107,7 @@ *

    Use {@link #getStore()} to access and query the store directly *

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

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

    In order to collect pre saved metadata and avoid re-scanning, use {@link #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). @@ -100,7 +115,7 @@ *

    For Javadoc, source code, and more information about Reflections Library, see http://github.com/ronmamo/reflections/ */ public class Reflections { - @Nullable public static Logger log = findLogger(Reflections.class); + public static Logger log = findLogger(Reflections.class); protected final transient Configuration configuration; protected Store store; @@ -111,13 +126,12 @@ public class Reflections { */ public Reflections(final Configuration configuration) { this.configuration = configuration; - store = new Store(configuration); + store = new Store(); 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(); @@ -137,7 +151,7 @@ public Reflections(final Configuration configuration) { * @param prefix package prefix, to be used with {@link org.reflections.util.ClasspathHelper#forPackage(String, ClassLoader...)} )} * @param scanners optionally supply scanners, otherwise defaults to {@link org.reflections.scanners.TypeAnnotationsScanner} and {@link org.reflections.scanners.SubTypesScanner} */ - public Reflections(final String prefix, @Nullable final Scanner... scanners) { + public Reflections(final String prefix, final Scanner... scanners) { this((Object) prefix, scanners); } @@ -170,7 +184,7 @@ public Reflections(final Object... params) { protected Reflections() { configuration = new ConfigurationBuilder(); - store = new Store(configuration); + store = new Store(); } // @@ -181,24 +195,22 @@ protected void scan() { } if (log != null && log.isDebugEnabled()) { - log.debug("going to scan these urls:\n{}", Joiner.on("\n").join(configuration.getUrls())); + log.debug("going to scan these urls: {}", configuration.getUrls()); } long time = System.currentTimeMillis(); int scannedUrls = 0; ExecutorService executorService = configuration.getExecutorService(); - List> futures = Lists.newArrayList(); + List> futures = new ArrayList<>(); for (final URL url : configuration.getUrls()) { try { if (executorService != null) { - futures.add(executorService.submit(new Runnable() { - public void run() { - if (log != null) { - log.debug("[{}] scanning {}", Thread.currentThread().toString(), url); - } - scan(url); + futures.add(executorService.submit(() -> { + if (log != null) { + log.debug("[{}] scanning {}", Thread.currentThread().toString(), url); } + scan(url); })); } else { scan(url); @@ -218,28 +230,29 @@ public void run() { } } - time = System.currentTimeMillis() - time; - //gracefully shutdown the parallel scanner executor service. if (executorService != null) { executorService.shutdown(); } if (log != null) { - int keys = 0; - int values = 0; - for (String index : store.keySet()) { - keys += store.get(index).keySet().size(); - values += store.get(index).size(); - } - - log.info(format("Reflections took %d ms to scan %d urls, producing %d keys and %d values %s", - time, scannedUrls, keys, values, - executorService != null && executorService instanceof ThreadPoolExecutor ? + log.info(format("Reflections took %d ms to scan %d urls, producing %s %s", + System.currentTimeMillis() - time, scannedUrls, producingDescription(store), + executorService instanceof ThreadPoolExecutor ? format("[using %d cores]", ((ThreadPoolExecutor) executorService).getMaximumPoolSize()) : "")); } } + private static String producingDescription(Store store) { + int keys = 0; + int values = 0; + for (String index : store.keySet()) { + keys += store.keys(index).size(); + values += store.values(index).size(); + } + return String.format("%d keys and %d values", keys, values); + } + protected void scan(URL url) { Vfs.Dir dir = Vfs.fromURL(url); @@ -249,12 +262,12 @@ protected void scan(URL url) { Predicate inputsFilter = configuration.getInputsFilter(); String path = file.getRelativePath(); String fqn = path.replace('/', '.'); - if (inputsFilter == null || inputsFilter.apply(path) || inputsFilter.apply(fqn)) { + if (inputsFilter == null || inputsFilter.test(path) || inputsFilter.test(fqn)) { Object classObject = null; for (Scanner scanner : configuration.getScanners()) { try { if (scanner.acceptsInput(path) || scanner.acceptsInput(fqn)) { - classObject = scanner.scan(file, classObject); + classObject = scanner.scan(file, classObject, store); } } catch (Exception e) { if (log != null) { @@ -286,7 +299,7 @@ public static Reflections collect() { * so that relevant urls could be found much faster * @param optionalSerializer - optionally supply one serializer instance. if not specified or null, {@link org.reflections.serializers.XmlSerializer} will be used */ - public static Reflections collect(final String packagePrefix, final Predicate resourceNameFilter, @Nullable Serializer... optionalSerializer) { + public static Reflections collect(final String packagePrefix, final Predicate resourceNameFilter, Serializer... optionalSerializer) { Serializer serializer = optionalSerializer != null && optionalSerializer.length == 1 ? optionalSerializer[0] : new XmlSerializer(); Collection urls = ClasspathHelper.forPackage(packagePrefix); @@ -307,16 +320,8 @@ public static Reflections collect(final String packagePrefix, final Predicate 1 ? "s" : "", keys, values, Joiner.on(", ").join(urls))); + log.info(format("Reflections took %d ms to collect %d url, producing %s", + System.currentTimeMillis() - start, urls.size(), producingDescription(reflections.store))); } return reflections; } @@ -354,16 +359,7 @@ public Reflections collect(final File file) { * merges a Reflections instance metadata into this instance */ public Reflections merge(final Reflections reflections) { - if (reflections.store != null) { - for (String indexName : reflections.store.keySet()) { - Multimap index = reflections.store.get(indexName); - for (String key : index.keySet()) { - for (String string : index.get(key)) { - store.getOrCreate(indexName).put(key, string); - } - } - } - } + store.merge(reflections.store); return this; } @@ -379,25 +375,22 @@ public Reflections merge(final Reflections reflections) { *

*/ public void expandSuperTypes() { - if (store.keySet().contains(index(SubTypesScanner.class))) { - Multimap mmap = store.get(index(SubTypesScanner.class)); - Sets.SetView keys = Sets.difference(mmap.keySet(), Sets.newHashSet(mmap.values())); - Multimap expand = HashMultimap.create(); - for (String key : keys) { - final Class type = forName(key, loaders()); - if (type != null) { - expandSupertypes(expand, key, type); - } + String index = index(SubTypesScanner.class); + Set keys = store.keys(index); + keys.removeAll(store.values(index)); + for (String key : keys) { + final Class type = forName(key, loaders()); + if (type != null) { + expandSupertypes(store, key, type); } - mmap.putAll(expand); } } - private void expandSupertypes(Multimap mmap, String key, Class type) { + private void expandSupertypes(Store store, String key, Class type) { for (Class supertype : ReflectionUtils.getSuperTypes(type)) { - if (mmap.put(supertype.getName(), key)) { + if (store.put(SubTypesScanner.class, supertype.getName(), key)) { if (log != null) log.debug("expanded subtype {} -> {}", supertype.getName(), key); - expandSupertypes(mmap, supertype.getName(), supertype); + expandSupertypes(store, supertype.getName(), supertype); } } } @@ -408,8 +401,8 @@ private void expandSupertypes(Multimap mmap, String key, Classdepends on SubTypesScanner configured */ public Set> getSubTypesOf(final Class type) { - return Sets.newHashSet(ReflectionUtils.forNames( - store.getAll(index(SubTypesScanner.class), Arrays.asList(type.getName())), loaders())); + return ReflectionUtils.forNames( + store.getAll(SubTypesScanner.class, Collections.singletonList(type.getName())), loaders()); } /** @@ -434,9 +427,9 @@ public Set> getTypesAnnotatedWith(final Class ann *

depends on TypeAnnotationsScanner and SubTypesScanner configured */ public Set> getTypesAnnotatedWith(final Class annotation, boolean honorInherited) { - Iterable annotated = store.get(index(TypeAnnotationsScanner.class), annotation.getName()); - Iterable classes = getAllAnnotated(annotated, annotation.isAnnotationPresent(Inherited.class), honorInherited); - return Sets.newHashSet(concat(forNames(annotated, loaders()), forNames(classes, loaders()))); + Set annotated = store.get(TypeAnnotationsScanner.class, annotation.getName()); + Set classes = getAllAnnotated(annotated, annotation.isAnnotationPresent(Inherited.class), honorInherited); + return new HashSet<>(concat(forNames(annotated, loaders()), forNames(classes, loaders()))); } /** @@ -454,28 +447,26 @@ public Set> getTypesAnnotatedWith(final Annotation annotation) { *

depends on TypeAnnotationsScanner configured */ public Set> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited) { - Iterable annotated = store.get(index(TypeAnnotationsScanner.class), annotation.annotationType().getName()); - Iterable> filter = filter(forNames(annotated, loaders()), withAnnotation(annotation)); - Iterable classes = getAllAnnotated(names(filter), annotation.annotationType().isAnnotationPresent(Inherited.class), honorInherited); - return Sets.newHashSet(concat(filter, forNames(filter(classes, not(in(Sets.newHashSet(annotated)))), loaders()))); + Set annotated = store.get(TypeAnnotationsScanner.class, annotation.annotationType().getName()); + Set> filter = filter(forNames(annotated, loaders()), withAnnotation(annotation)); + Set classes = getAllAnnotated(new HashSet<>(names(filter)), annotation.annotationType().isAnnotationPresent(Inherited.class), honorInherited); + return concat(filter, forNames(filter(classes, s -> !annotated.contains(s)), loaders())); } - protected Iterable getAllAnnotated(Iterable annotated, boolean inherited, boolean honorInherited) { + protected Set getAllAnnotated(Set annotated, boolean inherited, boolean honorInherited) { if (honorInherited) { if (inherited) { - Iterable subTypes = store.get(index(SubTypesScanner.class), filter(annotated, new Predicate() { - public boolean apply(@Nullable String input) { - final Class type = forName(input, loaders()); - return type != null && !type.isInterface(); - } + Set subTypes = store.get(SubTypesScanner.class, filter(annotated, (Predicate) input -> { + final Class type = forName(input, loaders()); + return type != null && !type.isInterface(); })); - return concat(subTypes, store.getAll(index(SubTypesScanner.class), subTypes)); + return concat(subTypes, store.getAll(SubTypesScanner.class, subTypes)); } else { return annotated; } } else { - Iterable subTypes = concat(annotated, store.getAll(index(TypeAnnotationsScanner.class), annotated)); - return concat(subTypes, store.getAll(index(SubTypesScanner.class), subTypes)); + Set subTypes = concat(annotated, store.getAll(TypeAnnotationsScanner.class, annotated)); + return concat(subTypes, store.getAll(SubTypesScanner.class, subTypes)); } } @@ -484,7 +475,7 @@ public boolean apply(@Nullable String input) { *

depends on MethodAnnotationsScanner configured */ public Set getMethodsAnnotatedWith(final Class annotation) { - Iterable methods = store.get(index(MethodAnnotationsScanner.class), annotation.getName()); + Set methods = store.get(MethodAnnotationsScanner.class, annotation.getName()); return getMethodsFromDescriptors(methods, loaders()); } @@ -498,23 +489,26 @@ public Set getMethodsAnnotatedWith(final Annotation annotation) { /** get methods with parameter types matching given {@code types}*/ public Set getMethodsMatchParams(Class... types) { - return getMethodsFromDescriptors(store.get(index(MethodParameterScanner.class), names(types).toString()), loaders()); + return getMethodsFromDescriptors(store.get(MethodParameterScanner.class, names(types).toString()), loaders()); } /** get methods with return type match given type */ public Set getMethodsReturn(Class returnType) { - return getMethodsFromDescriptors(store.get(index(MethodParameterScanner.class), names(returnType)), loaders()); + return getMethodsFromDescriptors(store.get(MethodParameterScanner.class, names(returnType)), loaders()); } /** get methods with any parameter annotated with given annotation */ public Set getMethodsWithAnyParamAnnotated(Class annotation) { - return getMethodsFromDescriptors(store.get(index(MethodParameterScanner.class), annotation.getName()), loaders()); + return getMethodsFromDescriptors(store.get(MethodParameterScanner.class, annotation.getName()), loaders()); } /** get methods with any parameter annotated with given annotation, including annotation member values matching */ public Set getMethodsWithAnyParamAnnotated(Annotation annotation) { - return filter(getMethodsWithAnyParamAnnotated(annotation.annotationType()), withAnyParameterAnnotation(annotation)); + return getMethodsWithAnyParamAnnotated(annotation.annotationType()) + .stream() + .filter(withAnyParameterAnnotation(annotation)) + .collect(Collectors.toSet()); } /** @@ -522,7 +516,7 @@ public Set getMethodsWithAnyParamAnnotated(Annotation annotation) { *

depends on MethodAnnotationsScanner configured */ public Set getConstructorsAnnotatedWith(final Class annotation) { - Iterable methods = store.get(index(MethodAnnotationsScanner.class), annotation.getName()); + Set methods = store.get(MethodAnnotationsScanner.class, annotation.getName()); return getConstructorsFromDescriptors(methods, loaders()); } @@ -536,17 +530,20 @@ public Set getConstructorsAnnotatedWith(final Annotation annotation /** get constructors with parameter types matching given {@code types}*/ public Set getConstructorsMatchParams(Class... types) { - return getConstructorsFromDescriptors(store.get(index(MethodParameterScanner.class), names(types).toString()), loaders()); + return getConstructorsFromDescriptors(store.get(MethodParameterScanner.class, names(types).toString()), loaders()); } /** get constructors with any parameter annotated with given annotation */ public Set getConstructorsWithAnyParamAnnotated(Class annotation) { - return getConstructorsFromDescriptors(store.get(index(MethodParameterScanner.class), annotation.getName()), loaders()); + return getConstructorsFromDescriptors(store.get(MethodParameterScanner.class, annotation.getName()), loaders()); } /** get constructors with any parameter annotated with given annotation, including annotation member values matching */ public Set getConstructorsWithAnyParamAnnotated(Annotation annotation) { - return filter(getConstructorsWithAnyParamAnnotated(annotation.annotationType()), withAnyParameterAnnotation(annotation)); + return getConstructorsWithAnyParamAnnotated(annotation.annotationType()) + .stream() + .filter(withAnyParameterAnnotation(annotation)) + .collect(Collectors.toSet()); } /** @@ -554,8 +551,8 @@ public Set getConstructorsWithAnyParamAnnotated(Annotation annotati *

depends on FieldAnnotationsScanner configured */ public Set getFieldsAnnotatedWith(final Class annotation) { - final Set result = Sets.newHashSet(); - for (String annotated : store.get(index(FieldAnnotationsScanner.class), annotation.getName())) { + final Set result = new HashSet<>(); + for (String annotated : store.get(FieldAnnotationsScanner.class, annotation.getName())) { result.add(getFieldFromString(annotated, loaders())); } return result; @@ -573,8 +570,8 @@ public Set getFieldsAnnotatedWith(final Annotation annotation) { *

depends on ResourcesScanner configured * */ public Set getResources(final Predicate namePredicate) { - Iterable resources = Iterables.filter(store.get(index(ResourcesScanner.class)).keySet(), namePredicate); - return Sets.newHashSet(store.get(index(ResourcesScanner.class), resources)); + Set resources = filter(store.keys(index(ResourcesScanner.class)), namePredicate); + return store.get(ResourcesScanner.class, resources); } /** get resources relative paths where simple name (key) matches given regular expression @@ -582,48 +579,44 @@ public Set getResources(final Predicate namePredicate) { *

Set xmls = reflections.getResources(".*\\.xml");
*/ public Set getResources(final Pattern pattern) { - return getResources(new Predicate() { - public boolean apply(String input) { - return pattern.matcher(input).matches(); - } - }); + return getResources(input -> pattern.matcher(input).matches()); } /** get parameter names of given {@code method} *

depends on MethodParameterNamesScanner configured */ public List getMethodParamNames(Method method) { - Iterable names = store.get(index(MethodParameterNamesScanner.class), name(method)); - return !Iterables.isEmpty(names) ? Arrays.asList(Iterables.getOnlyElement(names).split(", ")) : Arrays.asList(); + Set names = store.get(MethodParameterNamesScanner.class, name(method)); + return names.size() == 1 ? Arrays.asList(names.iterator().next().split(", ")) : Collections.emptyList(); } /** get parameter names of given {@code constructor} *

depends on MethodParameterNamesScanner configured */ public List getConstructorParamNames(Constructor constructor) { - Iterable names = store.get(index(MethodParameterNamesScanner.class), Utils.name(constructor)); - return !Iterables.isEmpty(names) ? Arrays.asList(Iterables.getOnlyElement(names).split(", ")) : Arrays.asList(); + Set names = store.get(MethodParameterNamesScanner.class, Utils.name(constructor)); + return names.size() == 1 ? Arrays.asList(names.iterator().next().split(", ")) : Collections.emptyList(); } /** get all given {@code field} usages in methods and constructors *

depends on MemberUsageScanner configured */ public Set getFieldUsage(Field field) { - return getMembersFromDescriptors(store.get(index(MemberUsageScanner.class), name(field))); + return getMembersFromDescriptors(store.get(MemberUsageScanner.class, name(field))); } /** get all given {@code method} usages in methods and constructors *

depends on MemberUsageScanner configured */ public Set getMethodUsage(Method method) { - return getMembersFromDescriptors(store.get(index(MemberUsageScanner.class), name(method))); + return getMembersFromDescriptors(store.get(MemberUsageScanner.class, name(method))); } /** get all given {@code constructors} usages in methods and constructors *

depends on MemberUsageScanner configured */ public Set getConstructorUsage(Constructor constructor) { - return getMembersFromDescriptors(store.get(index(MemberUsageScanner.class), name(constructor))); + return getMembersFromDescriptors(store.get(MemberUsageScanner.class, name(constructor))); } /** get all types scanned. this is effectively similar to getting all subtypes of Object. @@ -633,7 +626,7 @@ public Set getConstructorUsage(Constructor constructor) { * @return Set of String, and not of Class, in order to avoid definition of all types in PermGen */ public Set getAllTypes() { - Set allTypes = Sets.newHashSet(store.getAll(index(SubTypesScanner.class), Object.class.getName())); + Set allTypes = new HashSet<>(store.getAll(SubTypesScanner.class, Object.class.getName())); if (allTypes.isEmpty()) { throw new ReflectionsException("Couldn't find subtypes of Object. " + "Make sure SubTypesScanner initialized to include Object class - new SubTypesScanner(false)"); diff --git a/src/main/java/org/reflections/Store.java b/src/main/java/org/reflections/Store.java index 5f2d012c..008baf0b 100644 --- a/src/main/java/org/reflections/Store.java +++ b/src/main/java/org/reflections/Store.java @@ -1,10 +1,17 @@ package org.reflections; -import com.google.common.base.Supplier; -import com.google.common.collect.*; - -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +import static org.reflections.util.Utils.index; /** * stores metadata information in multimaps @@ -14,19 +21,10 @@ */ public class Store { - private transient boolean concurrent; - private final Map> storeMap; + private final ConcurrentHashMap>> storeMap; - //used via reflection - @SuppressWarnings("UnusedDeclaration") protected Store() { - storeMap = new HashMap>(); - concurrent = false; - } - - public Store(Configuration configuration) { - storeMap = new HashMap>(); - concurrent = configuration.getExecutorService() != null; + storeMap = new ConcurrentHashMap<>(); } /** return all indices */ @@ -34,26 +32,9 @@ public Set keySet() { return storeMap.keySet(); } - /** get or create the multimap object for the given {@code index} */ - public Multimap getOrCreate(String index) { - Multimap mmap = storeMap.get(index); - if (mmap == null) { - SetMultimap multimap = - Multimaps.newSetMultimap(new HashMap>(), - new Supplier>() { - public Set get() { - return Sets.newSetFromMap(new ConcurrentHashMap()); - } - }); - mmap = concurrent ? Multimaps.synchronizedSetMultimap(multimap) : multimap; - storeMap.put(index,mmap); - } - return mmap; - } - /** get the multimap object for the given {@code index}, otherwise throws a {@link org.reflections.ReflectionsException} */ - public Multimap get(String index) { - Multimap mmap = storeMap.get(index); + private Map> get(String index) { + Map> mmap = storeMap.get(index); if (mmap == null) { throw new ReflectionsException("Scanner " + index + " was not configured"); } @@ -61,47 +42,104 @@ public Multimap get(String index) { } /** get the values stored for the given {@code index} and {@code keys} */ - public Iterable get(String index, String... keys) { - return get(index, Arrays.asList(keys)); + public Set get(Class scannerClass, String keys) { + return get(index(scannerClass), keys); + } + + /** get the values stored for the given {@code index} and {@code keys} */ + public Set get(String index, String keys) { + return get(index, Collections.singletonList(keys)); } /** get the values stored for the given {@code index} and {@code keys} */ - public Iterable get(String index, Iterable keys) { - Multimap mmap = get(index); - IterableChain result = new IterableChain(); + public Set get(Class scannerClass, Iterable keys) { + return get(index(scannerClass), keys); + } + + /** get the values stored for the given {@code index} and {@code keys} */ + public Set get(String index, Iterable keys) { + Map> mmap = get(index); + Set result = new LinkedHashSet<>(); for (String key : keys) { - result.addAll(mmap.get(key)); + Collection values = mmap.get(key); + if (values != null) { + result.addAll(values); + } } return result; } /** recursively get the values stored for the given {@code index} and {@code keys}, including keys */ - private Iterable getAllIncluding(String index, Iterable keys, IterableChain result) { - result.addAll(keys); - for (String key : keys) { - Iterable values = get(index, key); - if (values.iterator().hasNext()) { - getAllIncluding(index, values, result); + private Set getAllIncluding(String index, Set keys) { + Map> mmap = get(index); + List workKeys = new ArrayList<>(keys); + + Set result = new HashSet<>(); + for (int i = 0; i < workKeys.size(); i++) { + String key = workKeys.get(i); + if (result.add(key)) { + Collection values = mmap.get(key); + if (values != null) { + workKeys.addAll(values); + } } } return result; } /** recursively get the values stored for the given {@code index} and {@code keys}, not including keys */ - public Iterable getAll(String index, String key) { - return getAllIncluding(index, get(index, key), new IterableChain()); + public Set getAll(Class scannerClass, String key) { + return getAll(index(scannerClass), key); + } + + /** recursively get the values stored for the given {@code index} and {@code keys}, not including keys */ + public Set getAll(String index, String key) { + return getAllIncluding(index, get(index, key)); } /** recursively get the values stored for the given {@code index} and {@code keys}, not including keys */ - public Iterable getAll(String index, Iterable keys) { - return getAllIncluding(index, get(index, keys), new IterableChain()); + public Set getAll(Class scannerClass, Iterable keys) { + return getAll(index(scannerClass), keys); } - private static class IterableChain implements Iterable { - private final List> chain = Lists.newArrayList(); + /** recursively get the values stored for the given {@code index} and {@code keys}, not including keys */ + public Set getAll(String index, Iterable keys) { + return getAllIncluding(index, get(index, keys)); + } - private void addAll(Iterable iterable) { chain.add(iterable); } + public Set keys(String index) { + Map> map = storeMap.get(index); + return map != null ? new HashSet<>(map.keySet()) : Collections.emptySet(); + } - public Iterator iterator() { return Iterables.concat(chain).iterator(); } + public Set values(String index) { + Map> map = storeMap.get(index); + return map != null ? map.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()) : Collections.emptySet(); + } + + // + public boolean put(Class scannerClass, String key, String value) { + return put(index(scannerClass), key, value); + } + + public boolean put(String index, String key, String value) { + return storeMap.computeIfAbsent(index, s -> new ConcurrentHashMap<>()) + .computeIfAbsent(key, s -> new ArrayList<>()) + .add(value); + } + + void merge(Store store) { + if (store != null) { + for (String indexName : store.keySet()) { + Map> index = store.get(indexName); + if (index != null) { + for (String key : index.keySet()) { + for (String string : index.get(key)) { + put(indexName, key, string); + } + } + } + } + } } } diff --git a/src/main/java/org/reflections/adapters/JavaReflectionAdapter.java b/src/main/java/org/reflections/adapters/JavaReflectionAdapter.java index ec2387ae..9c854c24 100644 --- a/src/main/java/org/reflections/adapters/JavaReflectionAdapter.java +++ b/src/main/java/org/reflections/adapters/JavaReflectionAdapter.java @@ -1,28 +1,30 @@ package org.reflections.adapters; -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; import org.reflections.util.Utils; import org.reflections.vfs.Vfs; -import javax.annotation.Nullable; import java.lang.annotation.Annotation; -import java.lang.reflect.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.reflections.ReflectionUtils.forName; +import static org.reflections.util.Utils.join; /** */ public class JavaReflectionAdapter implements MetadataAdapter { public List getFields(Class cls) { - return Lists.newArrayList(cls.getDeclaredFields()); + return Arrays.asList(cls.getDeclaredFields()); } public List getMethods(Class cls) { - List methods = Lists.newArrayList(); + List methods = new ArrayList<>(); methods.addAll(Arrays.asList(cls.getDeclaredMethods())); methods.addAll(Arrays.asList(cls.getDeclaredConstructors())); return methods; @@ -34,7 +36,7 @@ public String getMethodName(Member method) { } public List getParameterNames(final Member member) { - List result = Lists.newArrayList(); + List result = new ArrayList<>(); Class[] parameterTypes = member instanceof Method ? ((Method) member).getParameterTypes() : member instanceof Constructor ? ((Constructor) member).getParameterTypes() : null; @@ -84,7 +86,7 @@ public Class getOrCreateClassObject(Vfs.File file) throws Exception { return getOrCreateClassObject(file, null); } - public Class getOrCreateClassObject(Vfs.File file, @Nullable ClassLoader... loaders) throws Exception { + public Class getOrCreateClassObject(Vfs.File file, ClassLoader... loaders) throws Exception { String name = file.getRelativePath().replace("/", ".").replace(".class", ""); return forName(name, loaders); } @@ -94,7 +96,7 @@ public String getMethodModifier(Member method) { } public String getMethodKey(Class cls, Member method) { - return getMethodName(method) + "(" + Joiner.on(", ").join(getParameterNames(method)) + ")"; + return getMethodName(method) + "(" + join(getParameterNames(method), ", ") + ")"; } public String getMethodFullKey(Class cls, Member method) { @@ -120,7 +122,7 @@ public String getSuperclassName(Class cls) { public List getInterfacesNames(Class cls) { Class[] classes = cls.getInterfaces(); - List names = new ArrayList(classes != null ? classes.length : 0); + List names = new ArrayList<>(classes != null ? classes.length : 0); if (classes != null) for (Class cls1 : classes) names.add(cls1.getName()); return names; } @@ -131,7 +133,7 @@ public boolean acceptsInput(String file) { // private List getAnnotationNames(Annotation[] annotations) { - List names = new ArrayList(annotations.length); + List names = new ArrayList<>(annotations.length); for (Annotation annotation : annotations) { names.add(annotation.annotationType().getName()); } diff --git a/src/main/java/org/reflections/adapters/JavassistAdapter.java b/src/main/java/org/reflections/adapters/JavassistAdapter.java index d475ad24..7a3c286b 100644 --- a/src/main/java/org/reflections/adapters/JavassistAdapter.java +++ b/src/main/java/org/reflections/adapters/JavassistAdapter.java @@ -1,8 +1,12 @@ package org.reflections.adapters; -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; -import javassist.bytecode.*; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.AnnotationsAttribute; +import javassist.bytecode.ClassFile; +import javassist.bytecode.Descriptor; +import javassist.bytecode.FieldInfo; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.ParameterAnnotationsAttribute; import javassist.bytecode.annotation.Annotation; import org.reflections.ReflectionsException; import org.reflections.util.Utils; @@ -12,11 +16,13 @@ import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static javassist.bytecode.AccessFlag.isPrivate; import static javassist.bytecode.AccessFlag.isProtected; +import static org.reflections.util.Utils.join; /** * @@ -62,19 +68,18 @@ public List getMethodAnnotationNames(final MethodInfo method) { } public List getParameterAnnotationNames(final MethodInfo method, final int parameterIndex) { - List result = Lists.newArrayList(); + List result = new ArrayList<>(); - List parameterAnnotationsAttributes = Lists.newArrayList((ParameterAnnotationsAttribute) method.getAttribute(ParameterAnnotationsAttribute.visibleTag), + List parameterAnnotationsAttributes = Arrays.asList( + (ParameterAnnotationsAttribute) method.getAttribute(ParameterAnnotationsAttribute.visibleTag), (ParameterAnnotationsAttribute) method.getAttribute(ParameterAnnotationsAttribute.invisibleTag)); - if (parameterAnnotationsAttributes != null) { - for (ParameterAnnotationsAttribute parameterAnnotationsAttribute : parameterAnnotationsAttributes) { - if (parameterAnnotationsAttribute != null) { - Annotation[][] annotations = parameterAnnotationsAttribute.getAnnotations(); - if (parameterIndex < annotations.length) { - Annotation[] annotation = annotations[parameterIndex]; - result.addAll(getAnnotationNames(annotation)); - } + for (ParameterAnnotationsAttribute parameterAnnotationsAttribute : parameterAnnotationsAttributes) { + if (parameterAnnotationsAttribute != null) { + Annotation[][] annotations = parameterAnnotationsAttribute.getAnnotations(); + if (parameterIndex < annotations.length) { + Annotation[] annotation = annotations[parameterIndex]; + result.addAll(getAnnotationNames(annotation)); } } } @@ -113,7 +118,7 @@ public String getMethodModifier(MethodInfo method) { } public String getMethodKey(ClassFile cls, MethodInfo method) { - return getMethodName(method) + "(" + Joiner.on(", ").join(getParameterNames(method)) + ")"; + return getMethodName(method) + "(" + join(getParameterNames(method), ", ") + ")"; } public String getMethodFullKey(ClassFile cls, MethodInfo method) { @@ -148,7 +153,7 @@ public boolean acceptsInput(String file) { // private List getAnnotationNames(final AnnotationsAttribute... annotationsAttributes) { - List result = Lists.newArrayList(); + List result = new ArrayList<>(); if (annotationsAttributes != null) { for (AnnotationsAttribute annotationsAttribute : annotationsAttributes) { @@ -164,7 +169,7 @@ private List getAnnotationNames(final AnnotationsAttribute... annotation } private List getAnnotationNames(final Annotation[] annotations) { - List result = Lists.newArrayList(); + List result = new ArrayList<>(); for (Annotation annotation : annotations) { result.add(annotation.getTypeName()); @@ -174,11 +179,11 @@ private List getAnnotationNames(final Annotation[] annotations) { } private List splitDescriptorToTypeNames(final String descriptors) { - List result = Lists.newArrayList(); + List result = new ArrayList<>(); if (descriptors != null && descriptors.length() != 0) { - List indices = Lists.newArrayList(); + List indices = new ArrayList<>(); Descriptor.Iterator iterator = new Descriptor.Iterator(descriptors); while (iterator.hasNext()) { indices.add(iterator.next()); diff --git a/src/main/java/org/reflections/scanners/AbstractScanner.java b/src/main/java/org/reflections/scanners/AbstractScanner.java index 4f7e9536..bcde3ca2 100644 --- a/src/main/java/org/reflections/scanners/AbstractScanner.java +++ b/src/main/java/org/reflections/scanners/AbstractScanner.java @@ -1,28 +1,28 @@ package org.reflections.scanners; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Multimap; import org.reflections.Configuration; import org.reflections.ReflectionsException; +import org.reflections.Store; import org.reflections.adapters.MetadataAdapter; +import org.reflections.util.Utils; import org.reflections.vfs.Vfs; +import java.util.function.Predicate; + /** * */ -@SuppressWarnings({"RawUseOfParameterizedType", "unchecked"}) +@SuppressWarnings({"RawUseOfParameterizedType"}) public abstract class AbstractScanner implements Scanner { private Configuration configuration; - private Multimap store; - private Predicate resultFilter = Predicates.alwaysTrue(); //accept all by default + private Predicate resultFilter = s -> true; //accept all by default public boolean acceptsInput(String file) { return getMetadataAdapter().acceptsInput(file); } - public Object scan(Vfs.File file, Object classObject) { + public Object scan(Vfs.File file, Object classObject, Store store) { if (classObject == null) { try { classObject = configuration.getMetadataAdapter().getOrCreateClassObject(file); @@ -30,11 +30,15 @@ public Object scan(Vfs.File file, Object classObject) { throw new ReflectionsException("could not create class object from file " + file.getRelativePath(), e); } } - scan(classObject); + scan(classObject, store); return classObject; } - public abstract void scan(Object cls); + public abstract void scan(Object cls, Store store); + + protected void put(Store store, String key, String value) { + store.put(Utils.index(getClass()), key, value); + } // public Configuration getConfiguration() { @@ -45,14 +49,6 @@ public void setConfiguration(final Configuration configuration) { this.configuration = configuration; } - public Multimap getStore() { - return store; - } - - public void setStore(final Multimap store) { - this.store = store; - } - public Predicate getResultFilter() { return resultFilter; } @@ -67,7 +63,7 @@ public Scanner filterResultsBy(Predicate filter) { // public boolean acceptResult(final String fqn) { - return fqn != null && resultFilter.apply(fqn); + return fqn != null && resultFilter.test(fqn); } protected MetadataAdapter getMetadataAdapter() { diff --git a/src/main/java/org/reflections/scanners/FieldAnnotationsScanner.java b/src/main/java/org/reflections/scanners/FieldAnnotationsScanner.java index bd7d64c3..1f68470f 100644 --- a/src/main/java/org/reflections/scanners/FieldAnnotationsScanner.java +++ b/src/main/java/org/reflections/scanners/FieldAnnotationsScanner.java @@ -1,11 +1,13 @@ package org.reflections.scanners; +import org.reflections.Store; + import java.util.List; /** scans for field's annotations */ @SuppressWarnings({"unchecked"}) public class FieldAnnotationsScanner extends AbstractScanner { - public void scan(final Object cls) { + public void scan(final Object cls, Store store) { final String className = getMetadataAdapter().getClassName(cls); List fields = getMetadataAdapter().getFields(cls); for (final Object field : fields) { @@ -14,7 +16,7 @@ public void scan(final Object cls) { if (acceptResult(fieldAnnotation)) { String fieldName = getMetadataAdapter().getFieldName(field); - getStore().put(fieldAnnotation, String.format("%s.%s", className, fieldName)); + put(store, fieldAnnotation, String.format("%s.%s", className, fieldName)); } } } diff --git a/src/main/java/org/reflections/scanners/MemberUsageScanner.java b/src/main/java/org/reflections/scanners/MemberUsageScanner.java index daa3a956..df8967f2 100644 --- a/src/main/java/org/reflections/scanners/MemberUsageScanner.java +++ b/src/main/java/org/reflections/scanners/MemberUsageScanner.java @@ -1,12 +1,23 @@ package org.reflections.scanners; -import com.google.common.base.Joiner; -import javassist.*; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.LoaderClassPath; +import javassist.NotFoundException; import javassist.bytecode.MethodInfo; -import javassist.expr.*; +import javassist.expr.ConstructorCall; +import javassist.expr.ExprEditor; +import javassist.expr.FieldAccess; +import javassist.expr.MethodCall; +import javassist.expr.NewExpr; import org.reflections.ReflectionsException; +import org.reflections.Store; import org.reflections.util.ClasspathHelper; +import static org.reflections.util.Utils.join; + /** scans methods/constructors/fields usage *

depends on {@link org.reflections.adapters.JavassistAdapter} configured */ @SuppressWarnings("unchecked") @@ -14,14 +25,14 @@ public class MemberUsageScanner extends AbstractScanner { private ClassPool classPool; @Override - public void scan(Object cls) { + public void scan(Object cls, Store store) { try { CtClass ctClass = getClassPool().get(getMetadataAdapter().getClassName(cls)); for (CtBehavior member : ctClass.getDeclaredConstructors()) { - scanMember(member); + scanMember(member, store); } for (CtBehavior member : ctClass.getDeclaredMethods()) { - scanMember(member); + scanMember(member, store); } ctClass.detach(); } catch (Exception e) { @@ -29,7 +40,7 @@ public void scan(Object cls) { } } - void scanMember(CtBehavior member) throws CannotCompileException { + void scanMember(CtBehavior member, Store store) throws CannotCompileException { //key contains this$/val$ means local field/parameter closure final String key = member.getDeclaringClass().getName() + "." + member.getMethodInfo().getName() + "(" + parameterNames(member.getMethodInfo()) + ")"; //+ " #" + member.getMethodInfo().getLineNumber(0) @@ -37,7 +48,7 @@ void scanMember(CtBehavior member) throws CannotCompileException { @Override public void edit(NewExpr e) throws CannotCompileException { try { - put(e.getConstructor().getDeclaringClass().getName() + "." + "" + + put(store, e.getConstructor().getDeclaringClass().getName() + "." + "" + "(" + parameterNames(e.getConstructor().getMethodInfo()) + ")", e.getLineNumber(), key); } catch (NotFoundException e1) { throw new ReflectionsException("Could not find new instance usage in " + key, e1); @@ -47,7 +58,7 @@ public void edit(NewExpr e) throws CannotCompileException { @Override public void edit(MethodCall m) throws CannotCompileException { try { - put(m.getMethod().getDeclaringClass().getName() + "." + m.getMethodName() + + put(store, m.getMethod().getDeclaringClass().getName() + "." + m.getMethodName() + "(" + parameterNames(m.getMethod().getMethodInfo()) + ")", m.getLineNumber(), key); } catch (NotFoundException e) { throw new ReflectionsException("Could not find member " + m.getClassName() + " in " + key, e); @@ -57,7 +68,7 @@ public void edit(MethodCall m) throws CannotCompileException { @Override public void edit(ConstructorCall c) throws CannotCompileException { try { - put(c.getConstructor().getDeclaringClass().getName() + "." + "" + + put(store, c.getConstructor().getDeclaringClass().getName() + "." + "" + "(" + parameterNames(c.getConstructor().getMethodInfo()) + ")", c.getLineNumber(), key); } catch (NotFoundException e) { throw new ReflectionsException("Could not find member " + c.getClassName() + " in " + key, e); @@ -67,7 +78,7 @@ public void edit(ConstructorCall c) throws CannotCompileException { @Override public void edit(FieldAccess f) throws CannotCompileException { try { - put(f.getField().getDeclaringClass().getName() + "." + f.getFieldName(), f.getLineNumber(), key); + put(store, f.getField().getDeclaringClass().getName() + "." + f.getFieldName(), f.getLineNumber(), key); } catch (NotFoundException e) { throw new ReflectionsException("Could not find member " + f.getFieldName() + " in " + key, e); } @@ -75,14 +86,14 @@ public void edit(FieldAccess f) throws CannotCompileException { }); } - private void put(String key, int lineNumber, String value) { + private void put(Store store, String key, int lineNumber, String value) { if (acceptResult(key)) { - getStore().put(key, value + " #" + lineNumber); + put(store, key, value + " #" + lineNumber); } } String parameterNames(MethodInfo info) { - return Joiner.on(", ").join(getMetadataAdapter().getParameterNames(info)); + return join(getMetadataAdapter().getParameterNames(info), ", "); } private ClassPool getClassPool() { diff --git a/src/main/java/org/reflections/scanners/MethodAnnotationsScanner.java b/src/main/java/org/reflections/scanners/MethodAnnotationsScanner.java index 27470ffa..92ffc8c8 100644 --- a/src/main/java/org/reflections/scanners/MethodAnnotationsScanner.java +++ b/src/main/java/org/reflections/scanners/MethodAnnotationsScanner.java @@ -1,15 +1,17 @@ package org.reflections.scanners; +import org.reflections.Store; + import java.util.List; @SuppressWarnings({"unchecked"}) /** scans for method's annotations */ public class MethodAnnotationsScanner extends AbstractScanner { - public void scan(final Object cls) { + public void scan(final Object cls, Store store) { for (Object method : getMetadataAdapter().getMethods(cls)) { for (String methodAnnotation : (List) getMetadataAdapter().getMethodAnnotationNames(method)) { if (acceptResult(methodAnnotation)) { - getStore().put(methodAnnotation, getMetadataAdapter().getMethodFullKey(cls, method)); + put(store, methodAnnotation, getMetadataAdapter().getMethodFullKey(cls, method)); } } } diff --git a/src/main/java/org/reflections/scanners/MethodParameterNamesScanner.java b/src/main/java/org/reflections/scanners/MethodParameterNamesScanner.java index 6dd31d27..01d07fc0 100644 --- a/src/main/java/org/reflections/scanners/MethodParameterNamesScanner.java +++ b/src/main/java/org/reflections/scanners/MethodParameterNamesScanner.java @@ -1,33 +1,36 @@ package org.reflections.scanners; -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; +import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; import javassist.bytecode.MethodInfo; +import org.reflections.Store; import org.reflections.adapters.MetadataAdapter; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; +import static org.reflections.util.Utils.join; + /** scans methods/constructors and indexes parameter names */ @SuppressWarnings("unchecked") public class MethodParameterNamesScanner extends AbstractScanner { @Override - public void scan(Object cls) { + public void scan(Object cls, Store store) { final MetadataAdapter md = getMetadataAdapter(); for (Object method : md.getMethods(cls)) { String key = md.getMethodFullKey(cls, method); if (acceptResult(key)) { - LocalVariableAttribute table = (LocalVariableAttribute) ((MethodInfo) method).getCodeAttribute().getAttribute(LocalVariableAttribute.tag); - int length = table.tableLength(); + CodeAttribute codeAttribute = ((MethodInfo) method).getCodeAttribute(); + LocalVariableAttribute table = codeAttribute != null ? (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag) : null; + int length = table != null ? table.tableLength() : 0; int i = Modifier.isStatic(((MethodInfo) method).getAccessFlags()) ? 0 : 1; //skip this if (i < length) { - List names = new ArrayList(length - i); + List names = new ArrayList<>(length - i); while (i < length) names.add(((MethodInfo) method).getConstPool().getUtf8Info(table.nameIndex(i++))); - getStore().put(key, Joiner.on(", ").join(names)); + put(store, key, join(names, ", ")); } } } diff --git a/src/main/java/org/reflections/scanners/MethodParameterScanner.java b/src/main/java/org/reflections/scanners/MethodParameterScanner.java index 84eb8553..d106ad6e 100644 --- a/src/main/java/org/reflections/scanners/MethodParameterScanner.java +++ b/src/main/java/org/reflections/scanners/MethodParameterScanner.java @@ -1,5 +1,6 @@ package org.reflections.scanners; +import org.reflections.Store; import org.reflections.adapters.MetadataAdapter; import java.util.List; @@ -9,26 +10,26 @@ public class MethodParameterScanner extends AbstractScanner { @Override - public void scan(Object cls) { + public void scan(Object cls, Store store) { final MetadataAdapter md = getMetadataAdapter(); for (Object method : md.getMethods(cls)) { String signature = md.getParameterNames(method).toString(); if (acceptResult(signature)) { - getStore().put(signature, md.getMethodFullKey(cls, method)); + put(store, signature, md.getMethodFullKey(cls, method)); } String returnTypeName = md.getReturnTypeName(method); if (acceptResult(returnTypeName)) { - getStore().put(returnTypeName, md.getMethodFullKey(cls, method)); + put(store, returnTypeName, md.getMethodFullKey(cls, method)); } List parameterNames = md.getParameterNames(method); for (int i = 0; i < parameterNames.size(); i++) { for (Object paramAnnotation : md.getParameterAnnotationNames(method, i)) { if (acceptResult((String) paramAnnotation)) { - getStore().put((String) paramAnnotation, md.getMethodFullKey(cls, method)); + put(store, (String) paramAnnotation, md.getMethodFullKey(cls, method)); } } } diff --git a/src/main/java/org/reflections/scanners/ResourcesScanner.java b/src/main/java/org/reflections/scanners/ResourcesScanner.java index a10d9325..5d632708 100644 --- a/src/main/java/org/reflections/scanners/ResourcesScanner.java +++ b/src/main/java/org/reflections/scanners/ResourcesScanner.java @@ -1,5 +1,6 @@ package org.reflections.scanners; +import org.reflections.Store; import org.reflections.vfs.Vfs; /** collects all resources that are not classes in a collection @@ -9,12 +10,12 @@ public boolean acceptsInput(String file) { return !file.endsWith(".class"); //not a class } - @Override public Object scan(Vfs.File file, Object classObject) { - getStore().put(file.getName(), file.getRelativePath()); + @Override public Object scan(Vfs.File file, Object classObject, Store store) { + put(store, file.getName(), file.getRelativePath()); return classObject; } - public void scan(Object cls) { + public void scan(Object cls, Store store) { throw new UnsupportedOperationException(); //shouldn't get here } } diff --git a/src/main/java/org/reflections/scanners/Scanner.java b/src/main/java/org/reflections/scanners/Scanner.java index 2021e8dd..e6557ae8 100644 --- a/src/main/java/org/reflections/scanners/Scanner.java +++ b/src/main/java/org/reflections/scanners/Scanner.java @@ -1,11 +1,10 @@ package org.reflections.scanners; -import com.google.common.base.Predicate; -import com.google.common.collect.Multimap; import org.reflections.Configuration; +import org.reflections.Store; import org.reflections.vfs.Vfs; -import javax.annotation.Nullable; +import java.util.function.Predicate; /** * @@ -14,15 +13,11 @@ public interface Scanner { void setConfiguration(Configuration configuration); - Multimap getStore(); - - void setStore(Multimap store); - Scanner filterResultsBy(Predicate filter); boolean acceptsInput(String file); - Object scan(Vfs.File file, @Nullable Object classObject); + Object scan(Vfs.File file, Object classObject, Store store); boolean acceptResult(String fqn); } diff --git a/src/main/java/org/reflections/scanners/SubTypesScanner.java b/src/main/java/org/reflections/scanners/SubTypesScanner.java index e4bc9a7b..355421b0 100644 --- a/src/main/java/org/reflections/scanners/SubTypesScanner.java +++ b/src/main/java/org/reflections/scanners/SubTypesScanner.java @@ -1,5 +1,6 @@ package org.reflections.scanners; +import org.reflections.Store; import org.reflections.util.FilterBuilder; import java.util.List; @@ -21,17 +22,17 @@ public SubTypesScanner(boolean excludeObjectClass) { } @SuppressWarnings({"unchecked"}) - public void scan(final Object cls) { + public void scan(final Object cls, Store store) { String className = getMetadataAdapter().getClassName(cls); String superclass = getMetadataAdapter().getSuperclassName(cls); if (acceptResult(superclass)) { - getStore().put(superclass, className); + put(store, superclass, className); } for (String anInterface : (List) getMetadataAdapter().getInterfacesNames(cls)) { if (acceptResult(anInterface)) { - getStore().put(anInterface, className); + put(store, anInterface, className); } } } diff --git a/src/main/java/org/reflections/scanners/TypeAnnotationsScanner.java b/src/main/java/org/reflections/scanners/TypeAnnotationsScanner.java index 0681ac71..3d1d8941 100644 --- a/src/main/java/org/reflections/scanners/TypeAnnotationsScanner.java +++ b/src/main/java/org/reflections/scanners/TypeAnnotationsScanner.java @@ -1,19 +1,21 @@ package org.reflections.scanners; +import org.reflections.Store; + import java.lang.annotation.Inherited; import java.util.List; /** scans for class's annotations, where @Retention(RetentionPolicy.RUNTIME) */ @SuppressWarnings({"unchecked"}) public class TypeAnnotationsScanner extends AbstractScanner { - public void scan(final Object cls) { + public void scan(final Object cls, Store store) { final String className = getMetadataAdapter().getClassName(cls); for (String annotationType : (List) getMetadataAdapter().getClassAnnotationNames(cls)) { if (acceptResult(annotationType) || annotationType.equals(Inherited.class.getName())) { //as an exception, accept Inherited as well - getStore().put(annotationType, className); + put(store, annotationType, className); } } } diff --git a/src/main/java/org/reflections/scanners/TypeElementsScanner.java b/src/main/java/org/reflections/scanners/TypeElementsScanner.java index aba041f8..c8e39af8 100644 --- a/src/main/java/org/reflections/scanners/TypeElementsScanner.java +++ b/src/main/java/org/reflections/scanners/TypeElementsScanner.java @@ -1,6 +1,8 @@ package org.reflections.scanners; -import com.google.common.base.Joiner; +import org.reflections.Store; + +import static org.reflections.util.Utils.join; /** scans fields and methods and stores fqn as key and elements as values */ @SuppressWarnings({"unchecked"}) @@ -10,16 +12,16 @@ public class TypeElementsScanner extends AbstractScanner { private boolean includeAnnotations = true; private boolean publicOnly = true; - public void scan(Object cls) { + public void scan(Object cls, Store store) { String className = getMetadataAdapter().getClassName(cls); if (!acceptResult(className)) return; - getStore().put(className, ""); + put(store, className, ""); if (includeFields) { for (Object field : getMetadataAdapter().getFields(cls)) { String fieldName = getMetadataAdapter().getFieldName(field); - getStore().put(className, fieldName); + put(store, className, fieldName); } } @@ -27,15 +29,15 @@ public void scan(Object cls) { for (Object method : getMetadataAdapter().getMethods(cls)) { if (!publicOnly || getMetadataAdapter().isPublic(method)) { String methodKey = getMetadataAdapter().getMethodName(method) + "(" + - Joiner.on(", ").join(getMetadataAdapter().getParameterNames(method)) + ")"; - getStore().put(className, methodKey); + join(getMetadataAdapter().getParameterNames(method), ", ") + ")"; + put(store, className, methodKey); } } } if (includeAnnotations) { for (Object annotation : getMetadataAdapter().getClassAnnotationNames(cls)) { - getStore().put(className, "@" + annotation); + put(store, className, "@" + annotation); } } } diff --git a/src/main/java/org/reflections/scanners/TypesScanner.java b/src/main/java/org/reflections/scanners/TypesScanner.java deleted file mode 100644 index 6dffe7ce..00000000 --- a/src/main/java/org/reflections/scanners/TypesScanner.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.reflections.scanners; - -import org.reflections.ReflectionsException; -import org.reflections.vfs.Vfs; - -/** scans classes and stores fqn as key and full path as value. - *

Deprecated. use {@link org.reflections.scanners.TypeElementsScanner} */ -@Deprecated -public class TypesScanner extends AbstractScanner { - - @Override - public Object scan(Vfs.File file, Object classObject) { - classObject = super.scan(file, classObject); - String className = getMetadataAdapter().getClassName(classObject); - getStore().put(className, className); - return classObject; - } - - @Override - public void scan(Object cls) { - throw new UnsupportedOperationException("should not get here"); - } -} \ No newline at end of file diff --git a/src/main/java/org/reflections/serializers/JavaCodeSerializer.java b/src/main/java/org/reflections/serializers/JavaCodeSerializer.java index 50c51856..0249ec5a 100644 --- a/src/main/java/org/reflections/serializers/JavaCodeSerializer.java +++ b/src/main/java/org/reflections/serializers/JavaCodeSerializer.java @@ -1,12 +1,5 @@ package org.reflections.serializers; -import com.google.common.base.Joiner; -import com.google.common.base.Supplier; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; -import com.google.common.collect.Sets; -import com.google.common.io.Files; import org.reflections.ReflectionUtils; import org.reflections.Reflections; import org.reflections.ReflectionsException; @@ -20,19 +13,18 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.charset.Charset; -import java.util.Collection; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Date; -import java.util.HashMap; import java.util.LinkedList; import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; import static org.reflections.Reflections.log; -import static org.reflections.util.Utils.index; -import static org.reflections.util.Utils.prepareFile; -import static org.reflections.util.Utils.repeat; +import static org.reflections.util.Utils.*; /** Serialization of Reflections to java code *

Serializes types and types elements into interfaces respectively to fully qualified name, @@ -117,7 +109,7 @@ public File save(Reflections reflections, String name) { sb.append(toString(reflections)); sb.append("}\n"); - Files.write(sb.toString(), new File(filename), Charset.defaultCharset()); + Files.write(new File(filename).toPath(), sb.toString().getBytes(Charset.defaultCharset())); } catch (IOException e) { throw new RuntimeException(); @@ -127,19 +119,19 @@ public File save(Reflections reflections, String name) { } public String toString(Reflections reflections) { - if (reflections.getStore().get(index(TypeElementsScanner.class)).isEmpty()) { + if (reflections.getStore().keys(index(TypeElementsScanner.class)).isEmpty()) { if (log != null) log.warn("JavaCodeSerializer needs TypeElementsScanner configured"); } StringBuilder sb = new StringBuilder(); - List prevPaths = Lists.newArrayList(); + List prevPaths = new ArrayList<>(); int indent = 1; - List keys = Lists.newArrayList(reflections.getStore().get(index(TypeElementsScanner.class)).keySet()); + List keys = new ArrayList<>(reflections.getStore().keys(index(TypeElementsScanner.class))); Collections.sort(keys); for (String fqn : keys) { - List typePaths = Lists.newArrayList(fqn.split("\\.")); + List typePaths = Arrays.asList(fqn.split("\\.")); //skip indention int i = 0; @@ -161,15 +153,13 @@ public String toString(Reflections reflections) { String className = typePaths.get(typePaths.size() - 1); //get fields and methods - List annotations = Lists.newArrayList(); - List fields = Lists.newArrayList(); - final Multimap methods = Multimaps.newSetMultimap(new HashMap>(), new Supplier>() { - public Set get() { - return Sets.newHashSet(); - } - }); + List annotations = new ArrayList<>(); + List fields = new ArrayList<>(); + List methods = new ArrayList<>(); - for (String element : reflections.getStore().get(index(TypeElementsScanner.class), fqn)) { + Iterable members = reflections.getStore().get(index(TypeElementsScanner.class), fqn); + List sorted = StreamSupport.stream(members.spliterator(), false).sorted().collect(Collectors.toList()); + for (String element : sorted) { if (element.startsWith("@")) { annotations.add(element.substring(1)); } else if (element.contains("(")) { @@ -184,7 +174,11 @@ public Set get() { paramsDescriptor = tokenSeparator + params.replace(dotSeparator, tokenSeparator).replace(", ", doubleSeparator).replace("[]", arrayDescriptor); } String normalized = name + paramsDescriptor; - methods.put(name, normalized); + if (!methods.contains(name)) { + methods.add(name); + } else { + methods.add(normalized); + } } } else if (!Utils.isEmpty(element)) { //field @@ -207,13 +201,8 @@ public Set get() { //add methods if (!methods.isEmpty()) { sb.append(repeat("\t", indent++)).append("public interface methods {\n"); - for (Map.Entry entry : methods.entries()) { - String simpleName = entry.getKey(); - String normalized = entry.getValue(); - - String methodName = methods.get(simpleName).size() == 1 ? simpleName : normalized; - - methodName = getNonDuplicateName(methodName, fields); + for (String method : methods) { + String methodName = getNonDuplicateName(method, fields); sb.append(repeat("\t", indent)).append("public interface ").append(getNonDuplicateName(methodName, typePaths)).append(" {}\n"); } @@ -265,14 +254,14 @@ private String getNonDuplicateName(String candidate, List prev) { // public static Class resolveClassOf(final Class element) throws ClassNotFoundException { Class cursor = element; - LinkedList ognl = Lists.newLinkedList(); + LinkedList ognl = new LinkedList<>(); while (cursor != null) { ognl.addFirst(cursor.getSimpleName()); cursor = cursor.getDeclaringClass(); } - String classOgnl = Joiner.on(".").join(ognl.subList(1, ognl.size())).replace(".$", "$"); + String classOgnl = join(ognl.subList(1, ognl.size()), ".").replace(".$", "$"); return Class.forName(classOgnl); } diff --git a/src/main/java/org/reflections/serializers/JsonSerializer.java b/src/main/java/org/reflections/serializers/JsonSerializer.java index 52a0f175..371676e8 100644 --- a/src/main/java/org/reflections/serializers/JsonSerializer.java +++ b/src/main/java/org/reflections/serializers/JsonSerializer.java @@ -1,19 +1,16 @@ package org.reflections.serializers; -import com.google.common.base.Supplier; -import com.google.common.collect.*; -import com.google.common.io.Files; -import com.google.gson.*; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.reflections.Reflections; import org.reflections.util.Utils; -import java.io.*; -import java.lang.reflect.Type; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.nio.charset.Charset; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.nio.file.Files; /** serialization of Reflections to json * @@ -36,7 +33,7 @@ public Reflections read(InputStream inputStream) { public File save(Reflections reflections, String filename) { try { File file = Utils.prepareFile(filename); - Files.write(toString(reflections), file, Charset.defaultCharset()); + Files.write(file.toPath(), toString(reflections).getBytes(Charset.defaultCharset())); return file; } catch (IOException e) { throw new RuntimeException(e); @@ -49,30 +46,7 @@ public String toString(Reflections reflections) { private Gson getGson() { if (gson == null) { - gson = new GsonBuilder() - .registerTypeAdapter(Multimap.class, new com.google.gson.JsonSerializer() { - public JsonElement serialize(Multimap multimap, Type type, JsonSerializationContext jsonSerializationContext) { - return jsonSerializationContext.serialize(multimap.asMap()); - } - }) - .registerTypeAdapter(Multimap.class, new JsonDeserializer() { - public Multimap deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { - final SetMultimap map = Multimaps.newSetMultimap(new HashMap>(), new Supplier>() { - public Set get() { - return Sets.newHashSet(); - } - }); - for (Map.Entry entry : ((JsonObject) jsonElement).entrySet()) { - for (JsonElement element : (JsonArray) entry.getValue()) { - map.get(entry.getKey()).add(element.getAsString()); - } - } - return map; - } - }) - .setPrettyPrinting() - .create(); - + gson = new GsonBuilder().setPrettyPrinting().create(); } return gson; } diff --git a/src/main/java/org/reflections/serializers/XmlSerializer.java b/src/main/java/org/reflections/serializers/XmlSerializer.java index 6a40e09a..50f61298 100644 --- a/src/main/java/org/reflections/serializers/XmlSerializer.java +++ b/src/main/java/org/reflections/serializers/XmlSerializer.java @@ -13,7 +13,11 @@ import org.reflections.util.ConfigurationBuilder; import org.reflections.util.Utils; -import java.io.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; import java.lang.reflect.Constructor; /** serialization of Reflections to xml @@ -54,7 +58,7 @@ public Reflections read(InputStream inputStream) { Element values = entry.element("values"); for (Object o3 : values.elements()) { Element value = (Element) o3; - reflections.getStore().getOrCreate(index.getName()).put(key.getText(), value.getText()); + reflections.getStore().put(index.getName(), key.getText(), value.getText()); } } } @@ -106,11 +110,11 @@ private Document createDocument(final Reflections reflections) { Element root = document.addElement("Reflections"); for (String indexName : map.keySet()) { Element indexElement = root.addElement(indexName); - for (String key : map.get(indexName).keySet()) { + for (String key : map.keys(indexName)) { Element entryElement = indexElement.addElement("entry"); entryElement.addElement("key").setText(key); Element valuesElement = entryElement.addElement("values"); - for (String value : map.get(indexName).get(key)) { + for (String value : map.get(indexName, key)) { valuesElement.addElement("value").setText(value); } } diff --git a/src/main/java/org/reflections/util/ClasspathHelper.java b/src/main/java/org/reflections/util/ClasspathHelper.java index 4945e309..ecbd5d79 100644 --- a/src/main/java/org/reflections/util/ClasspathHelper.java +++ b/src/main/java/org/reflections/util/ClasspathHelper.java @@ -10,7 +10,14 @@ import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Enumeration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; @@ -94,7 +101,7 @@ public static Collection forPackage(String name, ClassLoader... classLoader * @return the collection of URLs, not null */ public static Collection forResource(String resourceName, ClassLoader... classLoaders) { - final List result = new ArrayList(); + final List result = new ArrayList<>(); final ClassLoader[] loaders = classLoaders(classLoaders); for (ClassLoader classLoader : loaders) { try { @@ -175,7 +182,7 @@ public static Collection forClassLoader() { * @return the collection of URLs, not null */ public static Collection forClassLoader(ClassLoader... classLoaders) { - final Collection result = new ArrayList(); + final Collection result = new ArrayList<>(); final ClassLoader[] loaders = classLoaders(classLoaders); for (ClassLoader classLoader : loaders) { while (classLoader != null) { @@ -201,7 +208,7 @@ public static Collection forClassLoader(ClassLoader... classLoaders) { * @return the collection of URLs, not null */ public static Collection forJavaClassPath() { - Collection urls = new ArrayList(); + Collection urls = new ArrayList<>(); String javaClassPath = System.getProperty("java.class.path"); if (javaClassPath != null) { for (String path : javaClassPath.split(File.pathSeparator)) { @@ -227,7 +234,7 @@ public static Collection forJavaClassPath() { * @return the collection of URLs, not null */ public static Collection forWebInfLib(final ServletContext servletContext) { - final Collection urls = new ArrayList(); + final Collection urls = new ArrayList<>(); Set resourcePaths = servletContext.getResourcePaths("/WEB-INF/lib"); if (resourcePaths == null) { return urls; @@ -286,7 +293,7 @@ public static Collection forManifest() { * @return the collection of URLs, not null */ public static Collection forManifest(final URL url) { - final Collection result = new ArrayList(); + final Collection result = new ArrayList<>(); result.add(url); try { final String part = cleanPath(url); @@ -323,7 +330,7 @@ public static Collection forManifest(final URL url) { * @return the collection of URLs, not null */ public static Collection forManifest(final Iterable urls) { - Collection result = new ArrayList(); + Collection result = new ArrayList<>(); // determine if any of the URLs are JARs, and get any dependencies for (URL url : urls) { result.addAll(forManifest(url)); @@ -385,7 +392,7 @@ private static String resourceName(String name) { //http://michaelscharf.blogspot.co.il/2006/11/javaneturlequals-and-hashcode-make.html private static Collection distinctUrls(Collection urls) { - Map distinct = new LinkedHashMap(urls.size()); + Map distinct = new LinkedHashMap<>(urls.size()); for (URL url : urls) { distinct.put(url.toExternalForm(), url); } diff --git a/src/main/java/org/reflections/util/ConfigurationBuilder.java b/src/main/java/org/reflections/util/ConfigurationBuilder.java index 5627f672..b61a28b3 100644 --- a/src/main/java/org/reflections/util/ConfigurationBuilder.java +++ b/src/main/java/org/reflections/util/ConfigurationBuilder.java @@ -1,10 +1,5 @@ package org.reflections.util; -import com.google.common.base.Predicate; -import com.google.common.collect.Lists; -import com.google.common.collect.ObjectArrays; -import com.google.common.collect.Sets; -import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.reflections.Configuration; import org.reflections.Reflections; import org.reflections.ReflectionsException; @@ -17,15 +12,19 @@ import org.reflections.serializers.Serializer; import org.reflections.serializers.XmlSerializer; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; +import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; +import java.util.stream.Stream; /** * a fluent builder for {@link org.reflections.Configuration}, to be used for constructing a {@link org.reflections.Reflections} instance @@ -43,18 +42,18 @@ * {@link #serializer} is {@link org.reflections.serializers.XmlSerializer} */ public class ConfigurationBuilder implements Configuration { - @Nonnull private Set scanners; - @Nonnull private Set urls; + private Set scanners; + private Set urls; /*lazy*/ protected MetadataAdapter metadataAdapter; - @Nullable private Predicate inputsFilter; + private Predicate inputsFilter; /*lazy*/ private Serializer serializer; - @Nullable private ExecutorService executorService; - @Nullable private ClassLoader[] classLoaders; + private ExecutorService executorService; + private ClassLoader[] classLoaders; private boolean expandSuperTypes = true; public ConfigurationBuilder() { - scanners = Sets.newHashSet(new TypeAnnotationsScanner(), new SubTypesScanner()); - urls = Sets.newHashSet(); + scanners = new HashSet<>(Arrays.asList(new TypeAnnotationsScanner(), new SubTypesScanner())); + urls = new HashSet<>(); } /** constructs a {@link ConfigurationBuilder} using the given parameters, in a non statically typed way. @@ -72,11 +71,11 @@ public ConfigurationBuilder() { *

use any parameter type in any order. this constructor uses instanceof on each param and instantiate a {@link ConfigurationBuilder} appropriately. * */ @SuppressWarnings("unchecked") - public static ConfigurationBuilder build(final @Nullable Object... params) { + public static ConfigurationBuilder build(final Object... params) { ConfigurationBuilder builder = new ConfigurationBuilder(); //flatten - List parameters = Lists.newArrayList(); + List parameters = new ArrayList<>(); if (params != null) { for (Object param : params) { if (param != null) { @@ -87,12 +86,12 @@ public static ConfigurationBuilder build(final @Nullable Object... params) { } } - List loaders = Lists.newArrayList(); + List loaders = new ArrayList<>(); for (Object param : parameters) if (param instanceof ClassLoader) loaders.add((ClassLoader) param); ClassLoader[] classLoaders = loaders.isEmpty() ? null : loaders.toArray(new ClassLoader[loaders.size()]); FilterBuilder filter = new FilterBuilder(); - List scanners = Lists.newArrayList(); + List scanners = new ArrayList<>(); for (Object param : parameters) { if (param instanceof String) { @@ -136,24 +135,22 @@ public ConfigurationBuilder forPackages(String... packages) { return this; } - @Nonnull public Set getScanners() { return scanners; } /** set the scanners instances for scanning different metadata */ - public ConfigurationBuilder setScanners(@Nonnull final Scanner... scanners) { + public ConfigurationBuilder setScanners(final Scanner... scanners) { this.scanners.clear(); return addScanners(scanners); } /** set the scanners instances for scanning different metadata */ public ConfigurationBuilder addScanners(final Scanner... scanners) { - this.scanners.addAll(Sets.newHashSet(scanners)); + this.scanners.addAll(Arrays.asList(scanners)); return this; } - @Nonnull public Set getUrls() { return urls; } @@ -161,8 +158,8 @@ public Set getUrls() { /** set the urls to be scanned *

use {@link org.reflections.util.ClasspathHelper} convenient methods to get the relevant urls * */ - public ConfigurationBuilder setUrls(@Nonnull final Collection urls) { - this.urls = Sets.newHashSet(urls); + public ConfigurationBuilder setUrls(final Collection urls) { + this.urls = new HashSet<>(urls); return this; } @@ -170,7 +167,7 @@ public ConfigurationBuilder setUrls(@Nonnull final Collection urls) { *

use {@link org.reflections.util.ClasspathHelper} convenient methods to get the relevant urls * */ public ConfigurationBuilder setUrls(final URL... urls) { - this.urls = Sets.newHashSet(urls); + this.urls = new HashSet<>(Arrays.asList(urls)); return this; } @@ -186,7 +183,7 @@ public ConfigurationBuilder addUrls(final Collection urls) { *

use {@link org.reflections.util.ClasspathHelper} convenient methods to get the relevant urls * */ public ConfigurationBuilder addUrls(final URL... urls) { - this.urls.addAll(Sets.newHashSet(urls)); + this.urls.addAll(new HashSet<>(Arrays.asList(urls))); return this; } @@ -212,31 +209,29 @@ public ConfigurationBuilder setMetadataAdapter(final MetadataAdapter metadataAda return this; } - @Nullable public Predicate getInputsFilter() { return inputsFilter; } /** sets the input filter for all resources to be scanned. - *

supply a {@link com.google.common.base.Predicate} or use the {@link FilterBuilder}*/ - public void setInputsFilter(@Nullable Predicate inputsFilter) { + *

supply a {@link Predicate} or use the {@link FilterBuilder}*/ + public void setInputsFilter(Predicate inputsFilter) { this.inputsFilter = inputsFilter; } /** sets the input filter for all resources to be scanned. - *

supply a {@link com.google.common.base.Predicate} or use the {@link FilterBuilder}*/ + *

supply a {@link Predicate} or use the {@link FilterBuilder}*/ public ConfigurationBuilder filterInputsBy(Predicate inputsFilter) { this.inputsFilter = inputsFilter; return this; } - @Nullable public ExecutorService getExecutorService() { return executorService; } /** sets the executor service used for scanning. */ - public ConfigurationBuilder setExecutorService(@Nullable ExecutorService executorService) { + public ConfigurationBuilder setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } @@ -251,8 +246,17 @@ public ConfigurationBuilder useParallelExecutor() { * the executor service spawns daemon threads by default. *

default is ThreadPoolExecutor with a single core */ public ConfigurationBuilder useParallelExecutor(final int availableProcessors) { - ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("org.reflections-scanner-%d").build(); - setExecutorService(Executors.newFixedThreadPool(availableProcessors, factory)); + ThreadFactory threadFactory = new ThreadFactory() { + private final AtomicInteger threadNumber = new AtomicInteger(1); + + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setName("org.reflections-scanner-" + threadNumber.getAndIncrement()); + t.setDaemon(true); + return t; + } + }; + setExecutorService(Executors.newFixedThreadPool(availableProcessors, threadFactory)); return this; } @@ -267,7 +271,6 @@ public ConfigurationBuilder setSerializer(Serializer serializer) { } /** get class loader, might be used for scanning or resolving methods/fields */ - @Nullable public ClassLoader[] getClassLoaders() { return classLoaders; } @@ -287,7 +290,7 @@ public ConfigurationBuilder setExpandSuperTypes(boolean expandSuperTypes) { } /** set class loader, might be used for resolving methods/fields */ - public void setClassLoaders(@Nullable ClassLoader[] classLoaders) { + public void setClassLoaders(ClassLoader[] classLoaders) { this.classLoaders = classLoaders; } @@ -298,7 +301,9 @@ public ConfigurationBuilder addClassLoader(ClassLoader classLoader) { /** add class loader, might be used for resolving methods/fields */ public ConfigurationBuilder addClassLoaders(ClassLoader... classLoaders) { - this.classLoaders = this.classLoaders == null ? classLoaders : ObjectArrays.concat(this.classLoaders, classLoaders, ClassLoader.class); + this.classLoaders = this.classLoaders == null ? classLoaders : + Stream.concat(Stream.concat(Arrays.stream(this.classLoaders), Arrays.stream(classLoaders)), Stream.of(ClassLoader.class)) + .distinct().toArray(ClassLoader[]::new); return this; } diff --git a/src/main/java/org/reflections/util/FilterBuilder.java b/src/main/java/org/reflections/util/FilterBuilder.java index d7e41a6a..f85bef9e 100644 --- a/src/main/java/org/reflections/util/FilterBuilder.java +++ b/src/main/java/org/reflections/util/FilterBuilder.java @@ -1,12 +1,11 @@ package org.reflections.util; -import com.google.common.base.Predicate; -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; import org.reflections.ReflectionsException; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.function.Predicate; import java.util.regex.Pattern; /** @@ -21,8 +20,8 @@ public class FilterBuilder implements Predicate { private final List> chain; - public FilterBuilder() {chain = Lists.newArrayList();} - private FilterBuilder(final Iterable> filters) {chain = Lists.newArrayList(filters);} + public FilterBuilder() {chain = new ArrayList<>();} + private FilterBuilder(final Collection> filters) {chain = new ArrayList<>(filters);} /** include a regular expression */ public FilterBuilder include(final String regex) {return add(new Include(regex));} @@ -54,18 +53,16 @@ public FilterBuilder includePackage(final String... prefixes) { public static String prefix(String qualifiedName) {return qualifiedName.replace(".","\\.") + ".*";} - @Override public String toString() {return Joiner.on(", ").join(chain);} + @Override public String toString() {return Utils.join(chain, ", ");} - public boolean apply(String regex) { - boolean accept = chain == null || chain.isEmpty() || chain.get(0) instanceof Exclude; + public boolean test(String regex) { + boolean accept = chain.isEmpty() || chain.get(0) instanceof Exclude; - if (chain != null) { - for (Predicate filter : chain) { - if (accept && filter instanceof Include) {continue;} //skip if this filter won't change - if (!accept && filter instanceof Exclude) {continue;} - accept = filter.apply(regex); - if (!accept && filter instanceof Exclude) {break;} //break on first exclusion - } + for (Predicate filter : chain) { + if (accept && filter instanceof Include) {continue;} //skip if this filter won't change + if (!accept && filter instanceof Exclude) {continue;} + accept = filter.test(regex); + if (!accept && filter instanceof Exclude) {break;} //break on first exclusion } return accept; } @@ -73,19 +70,18 @@ public boolean apply(String regex) { public abstract static class Matcher implements Predicate { final Pattern pattern; public Matcher(final String regex) {pattern = Pattern.compile(regex);} - public abstract boolean apply(String regex); @Override public String toString() {return pattern.pattern();} } public static class Include extends Matcher { public Include(final String patternString) {super(patternString);} - @Override public boolean apply(final String regex) {return pattern.matcher(regex).matches();} + @Override public boolean test(final String regex) {return pattern.matcher(regex).matches();} @Override public String toString() {return "+" + super.toString();} } public static class Exclude extends Matcher { public Exclude(final String patternString) {super(patternString);} - @Override public boolean apply(final String regex) {return !pattern.matcher(regex).matches();} + @Override public boolean test(final String regex) {return !pattern.matcher(regex).matches();} @Override public String toString() {return "-" + super.toString();} } @@ -102,7 +98,7 @@ public static class Exclude extends Matcher { * See also the more useful {@link FilterBuilder#parsePackages(String)} method. */ public static FilterBuilder parse(String includeExcludeString) { - List> filters = new ArrayList>(); + List> filters = new ArrayList<>(); if (!Utils.isEmpty(includeExcludeString)) { for (String string : includeExcludeString.split(",")) { @@ -143,14 +139,14 @@ public static FilterBuilder parse(String includeExcludeString) { * The input strings "-java" and "-java." are equivalent. */ public static FilterBuilder parsePackages(String includeExcludeString) { - List> filters = new ArrayList>(); + List> filters = new ArrayList<>(); if (!Utils.isEmpty(includeExcludeString)) { for (String string : includeExcludeString.split(",")) { String trimmed = string.trim(); char prefix = trimmed.charAt(0); String pattern = trimmed.substring(1); - if (pattern.endsWith(".") == false) { + if (!pattern.endsWith(".")) { pattern += "."; } pattern = prefix(pattern); diff --git a/src/main/java/org/reflections/util/Utils.java b/src/main/java/org/reflections/util/Utils.java index bf537652..3dbab487 100644 --- a/src/main/java/org/reflections/util/Utils.java +++ b/src/main/java/org/reflections/util/Utils.java @@ -1,14 +1,10 @@ package org.reflections.util; -import com.google.common.base.Joiner; -import com.google.common.collect.Sets; import org.reflections.Reflections; import org.reflections.ReflectionsException; -import org.reflections.scanners.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -18,8 +14,14 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; import static org.reflections.ReflectionUtils.forName; @@ -71,7 +73,7 @@ public static Member getMemberFromDescriptor(String descriptor, ClassLoader... c Class[] parameterTypes = null; if (!isEmpty(methodParameters)) { String[] parameterNames = methodParameters.split(","); - List> result = new ArrayList>(parameterNames.length); + List> result = new ArrayList<>(parameterNames.length); for (String name : parameterNames) { result.add(forName(name.trim(), classLoaders)); } @@ -96,7 +98,7 @@ public static Member getMemberFromDescriptor(String descriptor, ClassLoader... c } public static Set getMethodsFromDescriptors(Iterable annotatedWith, ClassLoader... classLoaders) { - Set result = Sets.newHashSet(); + Set result = new HashSet<>(); for (String annotated : annotatedWith) { if (!isConstructor(annotated)) { Method member = (Method) getMemberFromDescriptor(annotated, classLoaders); @@ -107,7 +109,7 @@ public static Set getMethodsFromDescriptors(Iterable annotatedWi } public static Set getConstructorsFromDescriptors(Iterable annotatedWith, ClassLoader... classLoaders) { - Set result = Sets.newHashSet(); + Set result = new HashSet<>(); for (String annotated : annotatedWith) { if (isConstructor(annotated)) { Constructor member = (Constructor) getMemberFromDescriptor(annotated, classLoaders); @@ -118,7 +120,7 @@ public static Set getConstructorsFromDescriptors(Iterable a } public static Set getMembersFromDescriptors(Iterable values, ClassLoader... classLoaders) { - Set result = Sets.newHashSet(); + Set result = new HashSet<>(); for (String value : values) { try { result.add(Utils.getMemberFromDescriptor(value, classLoaders)); @@ -149,7 +151,6 @@ public static void close(InputStream closeable) { } } - @Nullable public static Logger findLogger(Class aClass) { try { // This is to check whether an optional SLF4J binding is available. While SLF4J recommends that libraries @@ -182,7 +183,7 @@ public static String name(Class type) { public static List names(Iterable> types) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (Class type : types) result.add(name(type)); return result; } @@ -192,16 +193,41 @@ public static List names(Class... types) { } public static String name(Constructor constructor) { - return constructor.getName() + "." + "" + "(" + Joiner.on(", ").join(names(constructor.getParameterTypes())) + ")"; + return constructor.getName() + "." + "" + "(" + join(names(constructor.getParameterTypes()), ", ") + ")"; } public static String name(Method method) { - return method.getDeclaringClass().getName() + "." + method.getName() + "(" + Joiner.on(", ").join(names(method.getParameterTypes())) + ")"; + return method.getDeclaringClass().getName() + "." + method.getName() + "(" + join(names(method.getParameterTypes()), ", ") + ")"; } public static String name(Field field) { return field.getDeclaringClass().getName() + "." + field.getName(); } - public static String index(Class scannerClass) { return scannerClass.getSimpleName(); } + public static String index(Class scannerClass) { return scannerClass.getSimpleName(); } + + public static Predicate and(Predicate... predicates) { + return Arrays.stream(predicates).reduce(t -> true, Predicate::and); + } + + public static Stream stream(Iterable elements) { + return StreamSupport.stream(elements.spliterator(), false); + } + + public static String join(Collection elements, String delimiter) { + return elements.stream().map(Object::toString).collect(Collectors.joining(delimiter)); + } + + public static Set concat(Set forNames, Set forNames1) { + forNames.addAll(forNames1); + return forNames; + } + + public static Set filter(Collection result, Predicate... predicates) { + return result.stream().filter(and(predicates)).collect(Collectors.toSet()); + } + + public static Set filter(T[] result, Predicate... predicates) { + return Arrays.stream(result).filter(and(predicates)).collect(Collectors.toSet()); + } } diff --git a/src/main/java/org/reflections/vfs/JarInputDir.java b/src/main/java/org/reflections/vfs/JarInputDir.java index f04c6adf..aebf9184 100644 --- a/src/main/java/org/reflections/vfs/JarInputDir.java +++ b/src/main/java/org/reflections/vfs/JarInputDir.java @@ -1,6 +1,5 @@ package org.reflections.vfs; -import com.google.common.collect.AbstractIterator; import org.reflections.ReflectionsException; import org.reflections.util.Utils; @@ -28,35 +27,45 @@ public String getPath() { } public Iterable getFiles() { - return new Iterable() { - public Iterator iterator() { - return new AbstractIterator() { + return (Iterable) () -> new Iterator() { - { - try { jarInputStream = new JarInputStream(url.openConnection().getInputStream()); } - catch (Exception e) { throw new ReflectionsException("Could not open url connection", e); } - } + { + try { jarInputStream = new JarInputStream(url.openConnection().getInputStream()); } + catch (Exception e) { throw new ReflectionsException("Could not open url connection", e); } + } + + Vfs.File entry = null; + + @Override + public boolean hasNext() { + return entry != null || (entry = computeNext()) != null; + } + + @Override + public Vfs.File next() { + Vfs.File next = entry; + entry = null; + return next; + } - protected Vfs.File computeNext() { - while (true) { - try { - ZipEntry entry = jarInputStream.getNextJarEntry(); - if (entry == null) { - return endOfData(); - } + private Vfs.File computeNext() { + while (true) { + try { + ZipEntry entry = jarInputStream.getNextJarEntry(); + if (entry == null) { + return null; + } - long size = entry.getSize(); - if (size < 0) size = 0xffffffffl + size; //JDK-6916399 - nextCursor += size; - if (!entry.isDirectory()) { - return new JarInputFile(entry, JarInputDir.this, cursor, nextCursor); - } - } catch (IOException e) { - throw new ReflectionsException("could not get next zip entry", e); - } + long size = entry.getSize(); + if (size < 0) size = 0xffffffffl + size; //JDK-6916399 + nextCursor += size; + if (!entry.isDirectory()) { + return new JarInputFile(entry, JarInputDir.this, cursor, nextCursor); } + } catch (IOException e) { + throw new ReflectionsException("could not get next zip entry", e); } - }; + } } }; } diff --git a/src/main/java/org/reflections/vfs/SystemDir.java b/src/main/java/org/reflections/vfs/SystemDir.java index 46585e65..32c9fb75 100644 --- a/src/main/java/org/reflections/vfs/SystemDir.java +++ b/src/main/java/org/reflections/vfs/SystemDir.java @@ -1,13 +1,11 @@ package org.reflections.vfs; -import com.google.common.collect.AbstractIterator; -import com.google.common.collect.Lists; +import org.reflections.ReflectionsException; -import java.util.Collections; -import java.util.Iterator; -import java.util.Stack; -import java.util.List; import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Collections; /* * An implementation of {@link org.reflections.vfs.Vfs.Dir} for directory {@link java.io.File}. @@ -34,38 +32,18 @@ public Iterable getFiles() { if (file == null || !file.exists()) { return Collections.emptyList(); } - return new Iterable() { - public Iterator iterator() { - return new AbstractIterator() { - final Stack stack = new Stack(); - {stack.addAll(listFiles(file));} - - protected Vfs.File computeNext() { - while (!stack.isEmpty()) { - final File file = stack.pop(); - if (file.isDirectory()) { - stack.addAll(listFiles(file)); - } else { - return new SystemFile(SystemDir.this, file); - } - } - - return endOfData(); - } - }; + return () -> { + try { + return Files.walk(file.toPath()) + .filter(Files::isRegularFile) + .map(path -> (Vfs.File) new SystemFile(SystemDir.this, path.toFile())) + .iterator(); + } catch (IOException e) { + throw new ReflectionsException("could not get files for " + file, e); } }; } - private static List listFiles(final File file) { - File[] files = file.listFiles(); - - if (files != null) - return Lists.newArrayList(files); - else - return Lists.newArrayList(); - } - public void close() { } diff --git a/src/main/java/org/reflections/vfs/UrlTypeVFS.java b/src/main/java/org/reflections/vfs/UrlTypeVFS.java index e0be35cd..b3d07c5f 100644 --- a/src/main/java/org/reflections/vfs/UrlTypeVFS.java +++ b/src/main/java/org/reflections/vfs/UrlTypeVFS.java @@ -1,20 +1,19 @@ package org.reflections.vfs; +import org.reflections.Reflections; +import org.reflections.ReflectionsException; +import org.reflections.vfs.Vfs.Dir; +import org.reflections.vfs.Vfs.UrlType; + import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; +import java.util.function.Predicate; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.reflections.Reflections; -import org.reflections.ReflectionsException; -import org.reflections.vfs.Vfs.Dir; -import org.reflections.vfs.Vfs.UrlType; - -import com.google.common.base.Predicate; - /** * UrlType to be used by Reflections library. * This class handles the vfszip and vfsfile protocol of JBOSS files. @@ -68,7 +67,7 @@ URL replaceZipSeparators(String path, Predicate acceptFile) if (pos > 0) { File file = new File(path.substring(0, pos - 1)); - if (acceptFile.apply(file)) { return replaceZipSeparatorStartingFrom(path, pos); } + if (acceptFile.test(file)) { return replaceZipSeparatorStartingFrom(path, pos); } } } @@ -85,11 +84,7 @@ int findFirstMatchOfDeployableExtention(String path, int pos) { } } - Predicate realFile = new Predicate() { - public boolean apply(File file) { - return file.exists() && file.isFile(); - } - }; + Predicate realFile = file -> file.exists() && file.isFile(); URL replaceZipSeparatorStartingFrom(String path, int pos) throws MalformedURLException { diff --git a/src/main/java/org/reflections/vfs/Vfs.java b/src/main/java/org/reflections/vfs/Vfs.java index 215cd6b8..4c49edf6 100644 --- a/src/main/java/org/reflections/vfs/Vfs.java +++ b/src/main/java/org/reflections/vfs/Vfs.java @@ -1,23 +1,26 @@ package org.reflections.vfs; -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; import org.reflections.Reflections; import org.reflections.ReflectionsException; import org.reflections.util.ClasspathHelper; import org.reflections.util.Utils; -import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; -import java.net.*; +import java.net.JarURLConnection; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLDecoder; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; -import java.util.Iterator; import java.util.List; +import java.util.function.Predicate; import java.util.jar.JarFile; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; /** * a simple virtual file system bridge @@ -47,11 +50,11 @@ * * Vfs.Dir dir = Vfs.fromURL(new URL("http://mirrors.ibiblio.org/pub/mirrors/maven2/org/slf4j/slf4j-api/1.5.6/slf4j-api-1.5.6.jar")); * - *

use {@link org.reflections.vfs.Vfs#findFiles(java.util.Collection, com.google.common.base.Predicate)} to get an + *

use {@link org.reflections.vfs.Vfs#findFiles(java.util.Collection, java.util.function.Predicate)} to get an * iteration of files matching given name predicate over given list of urls */ public abstract class Vfs { - private static List defaultUrlTypes = Lists.newArrayList(DefaultUrlTypes.values()); + private static List defaultUrlTypes = new ArrayList<>(Arrays.asList(DefaultUrlTypes.values())); /** an abstract vfs dir */ public interface Dir { @@ -116,20 +119,18 @@ public static Dir fromURL(final URL url, final List urlTypes) { /** tries to create a Dir from the given url, using the given urlTypes*/ public static Dir fromURL(final URL url, final UrlType... urlTypes) { - return fromURL(url, Lists.newArrayList(urlTypes)); + return fromURL(url, Arrays.asList(urlTypes)); } /** return an iterable of all {@link org.reflections.vfs.Vfs.File} in given urls, starting with given packagePrefix and matching nameFilter */ public static Iterable findFiles(final Collection inUrls, final String packagePrefix, final Predicate nameFilter) { - Predicate fileNamePredicate = new Predicate() { - public boolean apply(File file) { - String path = file.getRelativePath(); - if (path.startsWith(packagePrefix)) { - String filename = path.substring(path.indexOf(packagePrefix) + packagePrefix.length()); - return !Utils.isEmpty(filename) && nameFilter.apply(filename.substring(1)); - } else { - return false; - } + Predicate fileNamePredicate = file -> { + String path = file.getRelativePath(); + if (path.startsWith(packagePrefix)) { + String filename = path.substring(path.indexOf(packagePrefix) + packagePrefix.length()); + return !Utils.isEmpty(filename) && nameFilter.test(filename.substring(1)); + } else { + return false; } }; @@ -137,29 +138,23 @@ public boolean apply(File file) { } /** return an iterable of all {@link org.reflections.vfs.Vfs.File} in given urls, matching filePredicate */ - public static Iterable findFiles(final Collection inUrls, final Predicate filePredicate) { - Iterable result = new ArrayList(); - - for (final URL url : inUrls) { - try { - result = Iterables.concat(result, - Iterables.filter(new Iterable() { - public Iterator iterator() { - return fromURL(url).getFiles().iterator(); - } - }, filePredicate)); - } catch (Throwable e) { - if (Reflections.log != null) { - Reflections.log.error("could not findFiles for url. continuing. [" + url + "]", e); - } - } - } - - return result; + public static Iterable findFiles(final Collection urls, final Predicate filePredicate) { + return () -> urls.stream() + .flatMap(url -> { + try { + return StreamSupport.stream(fromURL(url).getFiles().spliterator(), false); + } catch (Throwable e) { + if (Reflections.log != null) { + Reflections.log.error("could not findFiles for url. continuing. [" + url + "]", e); + } + return Stream.of(); + } + }) + .filter(filePredicate).iterator(); } /**try to get {@link java.io.File} from url*/ - public static @Nullable java.io.File getFile(URL url) { + public static java.io.File getFile(URL url) { java.io.File file; String path; @@ -209,7 +204,7 @@ private static boolean hasJarFileInPath(URL url) { *

bundle - for bundle protocol, using eclipse FileLocator (should be provided in classpath) *

jarInputStream - creates a {@link JarInputDir} over jar files, using Java's JarInputStream * */ - public static enum DefaultUrlTypes implements UrlType { + public enum DefaultUrlTypes implements UrlType { jarFile { public boolean matches(URL url) { return url.getProtocol().equals("file") && hasJarFileInPath(url); diff --git a/src/main/java/org/reflections/vfs/ZipDir.java b/src/main/java/org/reflections/vfs/ZipDir.java index 0beb8919..5e0dfff4 100644 --- a/src/main/java/org/reflections/vfs/ZipDir.java +++ b/src/main/java/org/reflections/vfs/ZipDir.java @@ -1,12 +1,9 @@ package org.reflections.vfs; -import com.google.common.collect.AbstractIterator; import org.reflections.Reflections; + import java.io.IOException; -import java.util.Enumeration; -import java.util.Iterator; import java.util.jar.JarFile; -import java.util.zip.ZipEntry; /** an implementation of {@link org.reflections.vfs.Vfs.Dir} for {@link java.util.zip.ZipFile} */ public class ZipDir implements Vfs.Dir { @@ -21,24 +18,10 @@ public String getPath() { } public Iterable getFiles() { - return new Iterable() { - public Iterator iterator() { - return new AbstractIterator() { - final Enumeration entries = jarFile.entries(); - - protected Vfs.File computeNext() { - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (!entry.isDirectory()) { - return new ZipFile(ZipDir.this, entry); - } - } - - return endOfData(); - } - }; - } - }; + return () -> jarFile.stream() + .filter(entry -> !entry.isDirectory()) + .map(entry -> (Vfs.File) new ZipFile(ZipDir.this, entry)) + .iterator(); } public void close() { diff --git a/src/test/java/org/reflections/ClasspathHelperTest.java b/src/test/java/org/reflections/ClasspathHelperTest.java index 1d93ab33..e6924f11 100644 --- a/src/test/java/org/reflections/ClasspathHelperTest.java +++ b/src/test/java/org/reflections/ClasspathHelperTest.java @@ -3,7 +3,6 @@ import org.junit.Assert; import org.junit.Test; import org.reflections.util.ClasspathHelper; -import sun.misc.ClassLoaderUtil; import java.net.MalformedURLException; import java.net.URL; diff --git a/src/test/java/org/reflections/FilterBuilderTest.java b/src/test/java/org/reflections/FilterBuilderTest.java index 94ecd272..0a959df1 100644 --- a/src/test/java/org/reflections/FilterBuilderTest.java +++ b/src/test/java/org/reflections/FilterBuilderTest.java @@ -1,11 +1,11 @@ package org.reflections; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import org.junit.Test; import org.reflections.util.FilterBuilder; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** * Test filtering */ @@ -14,150 +14,150 @@ public class FilterBuilderTest { @Test public void test_include() { FilterBuilder filter = new FilterBuilder().include("org\\.reflections.*"); - assertTrue(filter.apply("org.reflections.Reflections")); - assertTrue(filter.apply("org.reflections.foo.Reflections")); - assertFalse(filter.apply("org.foobar.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertTrue(filter.test("org.reflections.foo.Reflections")); + assertFalse(filter.test("org.foobar.Reflections")); } @Test public void test_includePackage() { FilterBuilder filter = new FilterBuilder().includePackage("org.reflections"); - assertTrue(filter.apply("org.reflections.Reflections")); - assertTrue(filter.apply("org.reflections.foo.Reflections")); - assertFalse(filter.apply("org.foobar.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertTrue(filter.test("org.reflections.foo.Reflections")); + assertFalse(filter.test("org.foobar.Reflections")); } @Test public void test_includePackageMultiple() { FilterBuilder filter = new FilterBuilder().includePackage("org.reflections", "org.foo"); - assertTrue(filter.apply("org.reflections.Reflections")); - assertTrue(filter.apply("org.reflections.foo.Reflections")); - assertTrue(filter.apply("org.foo.Reflections")); - assertTrue(filter.apply("org.foo.bar.Reflections")); - assertFalse(filter.apply("org.bar.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertTrue(filter.test("org.reflections.foo.Reflections")); + assertTrue(filter.test("org.foo.Reflections")); + assertTrue(filter.test("org.foo.bar.Reflections")); + assertFalse(filter.test("org.bar.Reflections")); } @Test public void test_includePackagebyClass() { FilterBuilder filter = new FilterBuilder().includePackage(Reflections.class); - assertTrue(filter.apply("org.reflections.Reflections")); - assertTrue(filter.apply("org.reflections.foo.Reflections")); - assertFalse(filter.apply("org.foobar.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertTrue(filter.test("org.reflections.foo.Reflections")); + assertFalse(filter.test("org.foobar.Reflections")); } //----------------------------------------------------------------------- @Test public void test_exclude() { FilterBuilder filter = new FilterBuilder().exclude("org\\.reflections.*"); - assertFalse(filter.apply("org.reflections.Reflections")); - assertFalse(filter.apply("org.reflections.foo.Reflections")); - assertTrue(filter.apply("org.foobar.Reflections")); + assertFalse(filter.test("org.reflections.Reflections")); + assertFalse(filter.test("org.reflections.foo.Reflections")); + assertTrue(filter.test("org.foobar.Reflections")); } @Test public void test_excludePackage() { FilterBuilder filter = new FilterBuilder().excludePackage("org.reflections"); - assertFalse(filter.apply("org.reflections.Reflections")); - assertFalse(filter.apply("org.reflections.foo.Reflections")); - assertTrue(filter.apply("org.foobar.Reflections")); + assertFalse(filter.test("org.reflections.Reflections")); + assertFalse(filter.test("org.reflections.foo.Reflections")); + assertTrue(filter.test("org.foobar.Reflections")); } @Test public void test_excludePackageByClass() { FilterBuilder filter = new FilterBuilder().excludePackage(Reflections.class); - assertFalse(filter.apply("org.reflections.Reflections")); - assertFalse(filter.apply("org.reflections.foo.Reflections")); - assertTrue(filter.apply("org.foobar.Reflections")); + assertFalse(filter.test("org.reflections.Reflections")); + assertFalse(filter.test("org.reflections.foo.Reflections")); + assertTrue(filter.test("org.foobar.Reflections")); } //----------------------------------------------------------------------- @Test public void test_parse_include() { FilterBuilder filter = FilterBuilder.parse("+org.reflections.*"); - assertTrue(filter.apply("org.reflections.Reflections")); - assertTrue(filter.apply("org.reflections.foo.Reflections")); - assertFalse(filter.apply("org.foobar.Reflections")); - assertTrue(filter.apply("org.reflectionsplus.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertTrue(filter.test("org.reflections.foo.Reflections")); + assertFalse(filter.test("org.foobar.Reflections")); + assertTrue(filter.test("org.reflectionsplus.Reflections")); } @Test public void test_parse_include_notRegex() { FilterBuilder filter = FilterBuilder.parse("+org.reflections"); - assertFalse(filter.apply("org.reflections.Reflections")); - assertFalse(filter.apply("org.reflections.foo.Reflections")); - assertFalse(filter.apply("org.foobar.Reflections")); - assertFalse(filter.apply("org.reflectionsplus.Reflections")); + assertFalse(filter.test("org.reflections.Reflections")); + assertFalse(filter.test("org.reflections.foo.Reflections")); + assertFalse(filter.test("org.foobar.Reflections")); + assertFalse(filter.test("org.reflectionsplus.Reflections")); } @Test public void test_parse_exclude() { FilterBuilder filter = FilterBuilder.parse("-org.reflections.*"); - assertFalse(filter.apply("org.reflections.Reflections")); - assertFalse(filter.apply("org.reflections.foo.Reflections")); - assertTrue(filter.apply("org.foobar.Reflections")); - assertFalse(filter.apply("org.reflectionsplus.Reflections")); + assertFalse(filter.test("org.reflections.Reflections")); + assertFalse(filter.test("org.reflections.foo.Reflections")); + assertTrue(filter.test("org.foobar.Reflections")); + assertFalse(filter.test("org.reflectionsplus.Reflections")); } @Test public void test_parse_exclude_notRegex() { FilterBuilder filter = FilterBuilder.parse("-org.reflections"); - assertTrue(filter.apply("org.reflections.Reflections")); - assertTrue(filter.apply("org.reflections.foo.Reflections")); - assertTrue(filter.apply("org.foobar.Reflections")); - assertTrue(filter.apply("org.reflectionsplus.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertTrue(filter.test("org.reflections.foo.Reflections")); + assertTrue(filter.test("org.foobar.Reflections")); + assertTrue(filter.test("org.reflectionsplus.Reflections")); } @Test public void test_parse_include_exclude() { FilterBuilder filter = FilterBuilder.parse("+org.reflections.*, -org.reflections.foo.*"); - assertTrue(filter.apply("org.reflections.Reflections")); - assertFalse(filter.apply("org.reflections.foo.Reflections")); - assertFalse(filter.apply("org.foobar.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertFalse(filter.test("org.reflections.foo.Reflections")); + assertFalse(filter.test("org.foobar.Reflections")); } //----------------------------------------------------------------------- @Test public void test_parsePackages_include() { FilterBuilder filter = FilterBuilder.parsePackages("+org.reflections"); - assertTrue(filter.apply("org.reflections.Reflections")); - assertTrue(filter.apply("org.reflections.foo.Reflections")); - assertFalse(filter.apply("org.foobar.Reflections")); - assertFalse(filter.apply("org.reflectionsplus.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertTrue(filter.test("org.reflections.foo.Reflections")); + assertFalse(filter.test("org.foobar.Reflections")); + assertFalse(filter.test("org.reflectionsplus.Reflections")); } @Test public void test_parsePackages_include_trailingDot() { FilterBuilder filter = FilterBuilder.parsePackages("+org.reflections."); - assertTrue(filter.apply("org.reflections.Reflections")); - assertTrue(filter.apply("org.reflections.foo.Reflections")); - assertFalse(filter.apply("org.foobar.Reflections")); - assertFalse(filter.apply("org.reflectionsplus.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertTrue(filter.test("org.reflections.foo.Reflections")); + assertFalse(filter.test("org.foobar.Reflections")); + assertFalse(filter.test("org.reflectionsplus.Reflections")); } @Test public void test_parsePackages_exclude() { FilterBuilder filter = FilterBuilder.parsePackages("-org.reflections"); - assertFalse(filter.apply("org.reflections.Reflections")); - assertFalse(filter.apply("org.reflections.foo.Reflections")); - assertTrue(filter.apply("org.foobar.Reflections")); - assertTrue(filter.apply("org.reflectionsplus.Reflections")); + assertFalse(filter.test("org.reflections.Reflections")); + assertFalse(filter.test("org.reflections.foo.Reflections")); + assertTrue(filter.test("org.foobar.Reflections")); + assertTrue(filter.test("org.reflectionsplus.Reflections")); } @Test public void test_parsePackages_exclude_trailingDot() { FilterBuilder filter = FilterBuilder.parsePackages("-org.reflections."); - assertFalse(filter.apply("org.reflections.Reflections")); - assertFalse(filter.apply("org.reflections.foo.Reflections")); - assertTrue(filter.apply("org.foobar.Reflections")); - assertTrue(filter.apply("org.reflectionsplus.Reflections")); + assertFalse(filter.test("org.reflections.Reflections")); + assertFalse(filter.test("org.reflections.foo.Reflections")); + assertTrue(filter.test("org.foobar.Reflections")); + assertTrue(filter.test("org.reflectionsplus.Reflections")); } @Test public void test_parsePackages_include_exclude() { FilterBuilder filter = FilterBuilder.parsePackages("+org.reflections, -org.reflections.foo"); - assertTrue(filter.apply("org.reflections.Reflections")); - assertFalse(filter.apply("org.reflections.foo.Reflections")); - assertFalse(filter.apply("org.foobar.Reflections")); + assertTrue(filter.test("org.reflections.Reflections")); + assertFalse(filter.test("org.reflections.foo.Reflections")); + assertFalse(filter.test("org.foobar.Reflections")); } } diff --git a/src/test/java/org/reflections/JavaCodeSerializerTest.java b/src/test/java/org/reflections/JavaCodeSerializerTest.java index 78bb8daf..d80e6d6a 100644 --- a/src/test/java/org/reflections/JavaCodeSerializerTest.java +++ b/src/test/java/org/reflections/JavaCodeSerializerTest.java @@ -1,6 +1,5 @@ package org.reflections; -import com.google.common.base.Predicate; import org.junit.BeforeClass; import org.junit.Test; import org.reflections.scanners.TypeElementsScanner; @@ -9,12 +8,11 @@ import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; -import static java.util.Arrays.asList; +import java.util.Collections; +import java.util.function.Predicate; + import static org.junit.Assert.assertEquals; -import static org.reflections.TestModel.AC2; -import static org.reflections.TestModel.C1; -import static org.reflections.TestModel.C2; -import static org.reflections.TestModel.C4; +import static org.reflections.TestModel.*; /** */ public class JavaCodeSerializerTest { @@ -26,7 +24,7 @@ public static void generateAndSave() { Reflections reflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(filter) .setScanners(new TypeElementsScanner().includeFields().publicOnly(false)) - .setUrls(asList(ClasspathHelper.forClass(TestModel.class)))); + .setUrls(Collections.singletonList(ClasspathHelper.forClass(TestModel.class)))); //save String filename = ReflectionsTest.getUserDir() + "/src/test/java/org.reflections.MyTestModelStore"; diff --git a/src/test/java/org/reflections/MyTestModelStore.java b/src/test/java/org/reflections/MyTestModelStore.java index 074e1299..4b2a6310 100644 --- a/src/test/java/org/reflections/MyTestModelStore.java +++ b/src/test/java/org/reflections/MyTestModelStore.java @@ -1,4 +1,4 @@ -//generated using Reflections JavaCodeSerializer [Tue Nov 11 12:45:43 CET 2014] +//generated using Reflections JavaCodeSerializer [Mon Jan 06 09:39:37 ICT 2020] package org.reflections; public interface MyTestModelStore { @@ -40,8 +40,8 @@ public interface java_lang_annotation_Retention {} } public interface TestModel$AI1 { public interface annotations { - public interface org_reflections_TestModel$MAI1 {} public interface java_lang_annotation_Retention {} + public interface org_reflections_TestModel$MAI1 {} } } public interface TestModel$AI2 { @@ -60,8 +60,8 @@ public interface java_lang_annotation_Retention {} } public interface TestModel$C1 { public interface annotations { - public interface org_reflections_TestModel$AC1n {} public interface org_reflections_TestModel$AC1 {} + public interface org_reflections_TestModel$AC1n {} } } public interface TestModel$C2 { @@ -76,18 +76,18 @@ public interface org_reflections_TestModel$AC2 {} } public interface TestModel$C4 { public interface fields { - public interface f3 {} public interface f1 {} public interface f2 {} + public interface f3 {} } public interface methods { + public interface add {} public interface c2toC3 {} + public interface m1 {} public interface m1_int__java_lang_String$$ {} public interface m1_int$$$$__java_lang_String$$$$ {} - public interface m1 {} public interface m3 {} public interface m4 {} - public interface add {} } } public interface TestModel$C5 { @@ -127,8 +127,8 @@ public interface fields { public interface c2 {} } public interface methods { - public interface method_java_lang_String {} public interface method {} + public interface method_java_lang_String {} } } public interface TestModel$Usage$C2 { diff --git a/src/test/java/org/reflections/ReflectionUtilsTest.java b/src/test/java/org/reflections/ReflectionUtilsTest.java index 39a192df..fd4fddce 100644 --- a/src/test/java/org/reflections/ReflectionUtilsTest.java +++ b/src/test/java/org/reflections/ReflectionUtilsTest.java @@ -1,13 +1,10 @@ package org.reflections; -import com.google.common.base.Function; -import com.google.common.collect.Sets; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Test; import org.reflections.scanners.FieldAnnotationsScanner; -import javax.annotation.Nullable; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Member; @@ -16,9 +13,10 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.HashSet; import java.util.Set; +import java.util.stream.Collectors; -import static com.google.common.collect.Collections2.transform; import static org.junit.Assert.*; import static org.reflections.ReflectionUtils.*; import static org.reflections.ReflectionsTest.are; @@ -63,7 +61,7 @@ public void getAllTest() { Class target = Collections.class; Object arg1 = Arrays.asList(1, 2, 3); - Set allMethods = Sets.newHashSet(); + Set allMethods = new HashSet<>(); for (Class type : getAllSuperTypes(arg1.getClass())) { allMethods.addAll(getAllMethods(target, withModifier(Modifier.STATIC), withParameters(type))); } @@ -86,7 +84,7 @@ public void withParametersAssignableFromTest() throws Exception { Class target = Collections.class; Object arg1 = Arrays.asList(1, 2, 3); - Set allMethods = Sets.newHashSet(); + Set allMethods = new HashSet<>(); for (Class type : getAllSuperTypes(arg1.getClass())) { allMethods.addAll(getAllMethods(target, withModifier(Modifier.STATIC), withParameters(type))); } @@ -101,7 +99,7 @@ public void withParametersAssignableFromTest() throws Exception { } } - @Test public void withReturn() throws Exception { + @Test public void withReturn() { Set returnMember = getAllMethods(Class.class, withReturnTypeAssignableTo(Member.class)); Set returnsAssignableToMember = getAllMethods(Class.class, withReturnType(Method.class)); @@ -119,16 +117,12 @@ public void getAllAndReflections() { Set af1 = reflections.getFieldsAnnotatedWith(TestModel.AF1.class); Set allFields = ReflectionUtils.getAll(af1, withModifier(Modifier.PROTECTED)); - assertTrue(allFields.size() == 1); + assertEquals(1, allFields.size()); assertThat(allFields, names("f2")); } private Set names(Set o) { - return Sets.newHashSet(transform(o, new Function() { - public String apply(@Nullable Member input) { - return input.getName(); - } - })); + return o.stream().map(Member::getName).collect(Collectors.toSet()); } private BaseMatcher> names(final String... namesArray) { diff --git a/src/test/java/org/reflections/ReflectionsCollectTest.java b/src/test/java/org/reflections/ReflectionsCollectTest.java index d6045f53..a71b3de2 100644 --- a/src/test/java/org/reflections/ReflectionsCollectTest.java +++ b/src/test/java/org/reflections/ReflectionsCollectTest.java @@ -1,18 +1,24 @@ package org.reflections; -import com.google.common.base.Predicate; import org.junit.BeforeClass; import org.junit.Test; -import org.reflections.scanners.*; +import org.reflections.scanners.MemberUsageScanner; +import org.reflections.scanners.MethodAnnotationsScanner; +import org.reflections.scanners.MethodParameterNamesScanner; +import org.reflections.scanners.MethodParameterScanner; +import org.reflections.scanners.ResourcesScanner; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.serializers.JsonSerializer; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; +import java.util.Collections; import java.util.Set; +import java.util.function.Predicate; import java.util.regex.Pattern; -import static java.util.Arrays.asList; import static org.junit.Assert.assertThat; import static org.reflections.util.Utils.index; @@ -34,7 +40,7 @@ public static void init() { ref.save(getUserDir() + "/target/test-classes" + "/META-INF/reflections/testModel-reflections.xml"); ref = new Reflections(new ConfigurationBuilder() - .setUrls(asList(ClasspathHelper.forClass(TestModel.class))) + .setUrls(Collections.singletonList(ClasspathHelper.forClass(TestModel.class))) .filterInputsBy(TestModelFilter) .setScanners( new MethodParameterScanner())); @@ -55,12 +61,12 @@ public void testResourcesScanner() { Reflections reflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(filter) .setScanners(new ResourcesScanner()) - .setUrls(asList(ClasspathHelper.forClass(TestModel.class)))); + .setUrls(Collections.singletonList(ClasspathHelper.forClass(TestModel.class)))); Set resolved = reflections.getResources(Pattern.compile(".*resource1-reflections\\.xml")); assertThat(resolved, are("META-INF/reflections/resource1-reflections.xml")); - Set resources = reflections.getStore().get(index(ResourcesScanner.class)).keySet(); + Set resources = reflections.getStore().keys(index(ResourcesScanner.class)); assertThat(resources, are("resource1-reflections.xml", "resource2-reflections.xml", "testModel-reflections.xml", "testModel-reflections.json")); } diff --git a/src/test/java/org/reflections/ReflectionsExpandSupertypesTest.java b/src/test/java/org/reflections/ReflectionsExpandSupertypesTest.java index c9e0d23b..f0ce1dac 100644 --- a/src/test/java/org/reflections/ReflectionsExpandSupertypesTest.java +++ b/src/test/java/org/reflections/ReflectionsExpandSupertypesTest.java @@ -1,6 +1,6 @@ package org.reflections; -import junit.framework.Assert; +import org.junit.Assert; import org.junit.Test; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; diff --git a/src/test/java/org/reflections/ReflectionsParallelTest.java b/src/test/java/org/reflections/ReflectionsParallelTest.java index 7548249d..8d74972a 100644 --- a/src/test/java/org/reflections/ReflectionsParallelTest.java +++ b/src/test/java/org/reflections/ReflectionsParallelTest.java @@ -1,14 +1,17 @@ package org.reflections; -import com.google.common.base.Predicate; import org.junit.BeforeClass; -import org.junit.Test; -import org.reflections.scanners.*; -import org.reflections.util.ConfigurationBuilder; +import org.reflections.scanners.FieldAnnotationsScanner; +import org.reflections.scanners.MemberUsageScanner; +import org.reflections.scanners.MethodAnnotationsScanner; +import org.reflections.scanners.MethodParameterNamesScanner; +import org.reflections.scanners.MethodParameterScanner; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; -import org.reflections.util.FilterBuilder; +import org.reflections.util.ConfigurationBuilder; -import static java.util.Arrays.asList; +import java.util.Collections; /** */ public class ReflectionsParallelTest extends ReflectionsTest { @@ -16,7 +19,7 @@ public class ReflectionsParallelTest extends ReflectionsTest { @BeforeClass public static void init() { reflections = new Reflections(new ConfigurationBuilder() - .setUrls(asList(ClasspathHelper.forClass(TestModel.class))) + .setUrls(Collections.singletonList(ClasspathHelper.forClass(TestModel.class))) .filterInputsBy(TestModelFilter) .setScanners( new SubTypesScanner(false), diff --git a/src/test/java/org/reflections/ReflectionsTest.java b/src/test/java/org/reflections/ReflectionsTest.java index 94727287..f345dfe1 100644 --- a/src/test/java/org/reflections/ReflectionsTest.java +++ b/src/test/java/org/reflections/ReflectionsTest.java @@ -1,30 +1,36 @@ package org.reflections; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.BeforeClass; import org.junit.Test; -import org.reflections.scanners.*; +import org.reflections.scanners.FieldAnnotationsScanner; +import org.reflections.scanners.MemberUsageScanner; +import org.reflections.scanners.MethodAnnotationsScanner; +import org.reflections.scanners.MethodParameterNamesScanner; +import org.reflections.scanners.MethodParameterScanner; +import org.reflections.scanners.ResourcesScanner; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; -import javax.annotation.Nullable; import java.io.File; import java.lang.annotation.Annotation; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Set; +import java.util.function.Predicate; import java.util.regex.Pattern; +import java.util.stream.Collectors; -import static java.util.Arrays.asList; import static org.junit.Assert.*; import static org.reflections.TestModel.*; import static org.reflections.util.Utils.index; @@ -40,7 +46,7 @@ public class ReflectionsTest { @BeforeClass public static void init() { reflections = new Reflections(new ConfigurationBuilder() - .setUrls(asList(ClasspathHelper.forClass(TestModel.class))) + .setUrls(Collections.singletonList(ClasspathHelper.forClass(TestModel.class))) .filterInputsBy(TestModelFilter) .setScanners( new SubTypesScanner(false), @@ -219,28 +225,28 @@ public void testResourcesScanner() { Reflections reflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(filter) .setScanners(new ResourcesScanner()) - .setUrls(asList(ClasspathHelper.forClass(TestModel.class)))); + .setUrls(Collections.singletonList(ClasspathHelper.forClass(TestModel.class)))); Set resolved = reflections.getResources(Pattern.compile(".*resource1-reflections\\.xml")); assertThat(resolved, are("META-INF/reflections/resource1-reflections.xml")); - Set resources = reflections.getStore().get(index(ResourcesScanner.class)).keySet(); + Set resources = reflections.getStore().keys(index(ResourcesScanner.class)); assertThat(resources, are("resource1-reflections.xml", "resource2-reflections.xml")); } @Test public void testMethodParameterNames() throws NoSuchMethodException { assertEquals(reflections.getMethodParamNames(C4.class.getDeclaredMethod("m3")), - Lists.newArrayList()); + Collections.emptyList()); assertEquals(reflections.getMethodParamNames(C4.class.getDeclaredMethod("m4", String.class)), - Lists.newArrayList("string")); + Collections.singletonList("string")); assertEquals(reflections.getMethodParamNames(C4.class.getDeclaredMethod("add", int.class, int.class)), - Lists.newArrayList("i1", "i2")); + Arrays.asList("i1", "i2")); assertEquals(reflections.getConstructorParamNames(C4.class.getDeclaredConstructor(String.class)), - Lists.newArrayList("f1")); + Collections.singletonList("f1")); } @Test @@ -282,7 +288,7 @@ public void testScannerNotConfigured() { public static String getUserDir() { File file = new File(System.getProperty("user.dir")); //a hack to fix user.dir issue(?) in surfire - if (Lists.newArrayList(file.list()).contains("reflections")) { + if (Arrays.asList(file.list()).contains("reflections")) { file = new File(file, "reflections"); } return file.getAbsolutePath(); @@ -309,6 +315,11 @@ public boolean matches(Object o) { Collection c2 = (Collection) o; return c1.containsAll(c2) && c2.containsAll(c1); } + + @Override + public void describeTo(Description description) { + description.appendText(Arrays.toString(ts)); + } }; } @@ -316,7 +327,7 @@ private Matcher>> annotatedWith(final Class a return new Match>>() { public boolean matches(Object o) { for (Class c : (Iterable>) o) { - if (!Iterables.contains(annotationTypes(Arrays.asList(c.getAnnotations())), annotation)) return false; + if (!annotationTypes(Arrays.asList(c.getAnnotations())).contains(annotation)) return false; } return true; } @@ -327,8 +338,8 @@ private Matcher>> metaAnnotatedWith(final Class>>() { public boolean matches(Object o) { for (Class c : (Iterable>) o) { - Set result = Sets.newHashSet(); - List stack = Lists.newArrayList(ReflectionUtils.getAllSuperTypes(c)); + Set result = new HashSet<>(); + List stack = new ArrayList<>(ReflectionUtils.getAllSuperTypes(c)); while (!stack.isEmpty()) { Class next = stack.remove(0); if (result.add(next)) { @@ -344,12 +355,7 @@ public boolean matches(Object o) { }; } - private Iterable> annotationTypes(Iterable annotations) { - return Iterables.transform(annotations, new Function>() { - @Nullable - public Class apply(@Nullable Annotation input) { - return input != null ? input.annotationType() : null; - } - }); + private List> annotationTypes(Collection annotations) { + return annotations.stream().filter(Objects::nonNull).map(Annotation::annotationType).collect(Collectors.toList()); } } diff --git a/src/test/java/org/reflections/ReflectionsThreadSafenessTest.java b/src/test/java/org/reflections/ReflectionsThreadSafenessTest.java index 078c21e7..b7f23e14 100644 --- a/src/test/java/org/reflections/ReflectionsThreadSafenessTest.java +++ b/src/test/java/org/reflections/ReflectionsThreadSafenessTest.java @@ -1,10 +1,10 @@ package org.reflections; -import com.google.common.collect.ImmutableMap; import org.junit.Test; import org.reflections.scanners.SubTypesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; +import org.slf4j.Logger; import java.util.Set; import java.util.concurrent.Callable; @@ -24,15 +24,12 @@ public class ReflectionsThreadSafenessTest { @Test public void reflections_scan_is_thread_safe() throws Exception { - Callable>> callable = new Callable>>() { - @Override - public Set> call() throws Exception { - final Reflections reflections = new Reflections(new ConfigurationBuilder() - .setUrls(singletonList(ClasspathHelper.forClass(ImmutableMap.class))) - .setScanners(new SubTypesScanner(false))); + Callable>> callable = () -> { + final Reflections reflections = new Reflections(new ConfigurationBuilder() + .setUrls(singletonList(ClasspathHelper.forClass(Logger.class))) + .setScanners(new SubTypesScanner(false))); - return reflections.getSubTypesOf(ImmutableMap.class); - } + return reflections.getSubTypesOf(Logger.class); }; final ExecutorService pool = Executors.newFixedThreadPool(2); diff --git a/src/test/java/org/reflections/VfsTest.java b/src/test/java/org/reflections/VfsTest.java index bd4bf66d..99ccf49c 100644 --- a/src/test/java/org/reflections/VfsTest.java +++ b/src/test/java/org/reflections/VfsTest.java @@ -1,138 +1,108 @@ package org.reflections; -import static java.text.MessageFormat.format; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.DataInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; -import java.util.jar.JarFile; - -import org.junit.Ignore; +import javassist.bytecode.ClassFile; import org.junit.Test; import org.reflections.adapters.JavassistAdapter; import org.reflections.util.ClasspathHelper; -import org.reflections.vfs.JarInputDir; import org.reflections.vfs.SystemDir; import org.reflections.vfs.Vfs; -import org.reflections.vfs.ZipDir; +import org.slf4j.Logger; -import com.google.common.base.Predicates; -import com.google.common.collect.Iterables; +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collection; -import javassist.bytecode.ClassFile; +import static java.text.MessageFormat.format; +import static org.junit.Assert.*; -/** */ +/** + * + */ public class VfsTest { @Test - public void allKindsOfShittyUrls() throws Exception { - JavassistAdapter mdAdapter = new JavassistAdapter(); - - { - URL jar1 = getSomeJar(); - assertTrue(jar1.toString().startsWith("file:")); - assertTrue(jar1.toString().contains(".jar")); + public void testJarFile() throws Exception { + URL url = new URL(ClasspathHelper.forClass(Logger.class).toExternalForm().replace("jar:", "")); + assertTrue(url.toString().startsWith("file:")); + assertTrue(url.toString().contains(".jar")); - assertTrue(Vfs.DefaultUrlTypes.jarFile.matches(jar1)); - assertFalse(Vfs.DefaultUrlTypes.jarUrl.matches(jar1)); - assertFalse(Vfs.DefaultUrlTypes.directory.matches(jar1)); + assertTrue(Vfs.DefaultUrlTypes.jarFile.matches(url)); + assertFalse(Vfs.DefaultUrlTypes.jarUrl.matches(url)); + assertFalse(Vfs.DefaultUrlTypes.directory.matches(url)); - Vfs.Dir dir = Vfs.DefaultUrlTypes.jarFile.createDir(jar1); - Vfs.File file = null; - for (Vfs.File f : dir.getFiles()) { - if (f.getRelativePath().endsWith(".class")) { file = f; break; } - } + Vfs.Dir dir = Vfs.DefaultUrlTypes.jarFile.createDir(url); + testVfsDir(dir); + } - ClassFile stringCF = mdAdapter.getOrCreateClassObject(file); - //noinspection UnusedDeclaration - String className = mdAdapter.getClassName(stringCF); - } + @Test + public void testJarUrl() throws Exception { + URL url = ClasspathHelper.forClass(Logger.class); + assertTrue(url.toString().startsWith("jar:file:")); + assertTrue(url.toString().contains(".jar!")); - { - URL rtJarUrl = ClasspathHelper.forClass(String.class); - assertTrue(rtJarUrl.toString().startsWith("jar:file:")); - assertTrue(rtJarUrl.toString().contains(".jar!")); + assertFalse(Vfs.DefaultUrlTypes.jarFile.matches(url)); + assertTrue(Vfs.DefaultUrlTypes.jarUrl.matches(url)); + assertFalse(Vfs.DefaultUrlTypes.directory.matches(url)); - assertFalse(Vfs.DefaultUrlTypes.jarFile.matches(rtJarUrl)); - assertTrue(Vfs.DefaultUrlTypes.jarUrl.matches(rtJarUrl)); - assertFalse(Vfs.DefaultUrlTypes.directory.matches(rtJarUrl)); + Vfs.Dir dir = Vfs.DefaultUrlTypes.jarUrl.createDir(url); + testVfsDir(dir); + } - Vfs.Dir dir = Vfs.DefaultUrlTypes.jarUrl.createDir(rtJarUrl); - Vfs.File file = null; - for (Vfs.File f : dir.getFiles()) { - if (f.getRelativePath().equals("java/lang/String.class")) { file = f; break; } - } + @Test + public void testDirectory() throws Exception { + URL url = ClasspathHelper.forClass(getClass()); + assertTrue(url.toString().startsWith("file:")); + assertFalse(url.toString().contains(".jar")); - ClassFile stringCF = mdAdapter.getOrCreateClassObject(file); - String className = mdAdapter.getClassName(stringCF); - assertTrue(className.equals("java.lang.String")); - } + assertFalse(Vfs.DefaultUrlTypes.jarFile.matches(url)); + assertFalse(Vfs.DefaultUrlTypes.jarUrl.matches(url)); + assertTrue(Vfs.DefaultUrlTypes.directory.matches(url)); - { - URL thisUrl = ClasspathHelper.forClass(getClass()); - assertTrue(thisUrl.toString().startsWith("file:")); - assertFalse(thisUrl.toString().contains(".jar")); + Vfs.Dir dir = Vfs.DefaultUrlTypes.directory.createDir(url); + testVfsDir(dir); + } - assertFalse(Vfs.DefaultUrlTypes.jarFile.matches(thisUrl)); - assertFalse(Vfs.DefaultUrlTypes.jarUrl.matches(thisUrl)); - assertTrue(Vfs.DefaultUrlTypes.directory.matches(thisUrl)); + @Test + public void testJarInputStream() throws Exception { + URL url = ClasspathHelper.forClass(Logger.class); + assertTrue(Vfs.DefaultUrlTypes.jarInputStream.matches(url)); + try { + testVfsDir(Vfs.DefaultUrlTypes.jarInputStream.createDir(url)); + fail(); + } catch (ReflectionsException e) { + // expected + } - Vfs.Dir dir = Vfs.DefaultUrlTypes.directory.createDir(thisUrl); - Vfs.File file = null; - for (Vfs.File f : dir.getFiles()) { - if (f.getRelativePath().equals("org/reflections/VfsTest.class")) { file = f; break; } - } + url = new URL(ClasspathHelper.forClass(Logger.class).toExternalForm().replace("jar:", "").replace(".jar!", ".jar")); + assertTrue(Vfs.DefaultUrlTypes.jarInputStream.matches(url)); + testVfsDir(Vfs.DefaultUrlTypes.jarInputStream.createDir(url)); - ClassFile stringCF = mdAdapter.getOrCreateClassObject(file); - String className = mdAdapter.getClassName(stringCF); - assertTrue(className.equals(getClass().getName())); - } - { - // create a file, then delete it so we can treat as a non-existing directory - File tempFile = File.createTempFile("nosuch", "dir"); - tempFile.delete(); - assertFalse(tempFile.exists()); - Vfs.Dir dir = Vfs.DefaultUrlTypes.directory.createDir(tempFile.toURL()); - assertNotNull(dir); - assertFalse(dir.getFiles().iterator().hasNext()); - assertNotNull(dir.getPath()); - assertNotNull(dir.toString()); - dir.close(); + url = ClasspathHelper.forClass(getClass()); + assertFalse(Vfs.DefaultUrlTypes.jarInputStream.matches(url)); + try { + testVfsDir(Vfs.DefaultUrlTypes.jarInputStream.createDir(url)); + fail(); + } catch (NullPointerException e) { + // expected } - } - @Test public void dirWithSpaces() { + @Test + public void dirWithSpaces() { Collection urls = ClasspathHelper.forPackage("dir+with spaces"); assertFalse(urls.isEmpty()); for (URL url : urls) { - testVfsDir(url); + Vfs.Dir dir = Vfs.fromURL(url); + assertNotNull(dir); + assertNotNull(dir.getFiles().iterator().next()); } } - @Test - public void vfsFromJar() { - testVfsDir(getSomeJar()); - } - - @Test - public void vfsFromDir() { - testVfsDir(getSomeDirectory()); - } - @Test public void vfsFromDirWithJarInName() throws MalformedURLException { String tmpFolder = System.getProperty("java.io.tmpdir"); - tmpFolder = tmpFolder.endsWith(File.separator) ? tmpFolder : tmpFolder + File.separator; + tmpFolder = tmpFolder.endsWith(File.separator) ? tmpFolder : tmpFolder + File.separator; String dirWithJarInName = tmpFolder + "tony.jarvis"; File newDir = new File(dirWithJarInName); newDir.mkdir(); @@ -146,139 +116,19 @@ public void vfsFromDirWithJarInName() throws MalformedURLException { newDir.delete(); } } - - @Test - public void vfsFromDirWithinAJarUrl() throws MalformedURLException { - URL directoryInJarUrl = ClasspathHelper.forClass(String.class); - assertTrue(directoryInJarUrl.toString().startsWith("jar:file:")); - assertTrue(directoryInJarUrl.toString().contains(".jar!")); - - String directoryInJarPath = directoryInJarUrl.toExternalForm().replaceFirst("jar:", ""); - int start = directoryInJarPath.indexOf(":") + 1; - int end = directoryInJarPath.indexOf(".jar!") + 4; - String expectedJarFile = directoryInJarPath.substring(start, end); - - Vfs.Dir dir = Vfs.fromURL(new URL(directoryInJarPath)); - - assertEquals(ZipDir.class, dir.getClass()); - assertEquals(expectedJarFile, dir.getPath()); - } - - @Test - public void vfsFromJarFileUrl() throws MalformedURLException { - testVfsDir(new URL("jar:file:" + getSomeJar().getPath() + "!/")); - } - - @Test - public void findFilesFromEmptyMatch() throws MalformedURLException { - final URL jar = getSomeJar(); - final Iterable files = Vfs.findFiles(java.util.Arrays.asList(jar), Predicates.alwaysTrue()); - assertNotNull(files); - assertTrue(files.iterator().hasNext()); - } - - private void testVfsDir(URL url) { - System.out.println("testVfsDir(" + url + ")"); - assertNotNull(url); - - Vfs.Dir dir = Vfs.fromURL(url); - assertNotNull(dir); - - Iterable files = dir.getFiles(); - Vfs.File first = files.iterator().next(); - assertNotNull(first); - - first.getName(); - try { - first.openInputStream(); - } catch (IOException e) { - throw new RuntimeException(e); - } - - dir.close(); - } - - @Test @Ignore - public void vfsFromHttpUrl() throws MalformedURLException { - Vfs.addDefaultURLTypes(new Vfs.UrlType() { - public boolean matches(URL url) {return url.getProtocol().equals("http");} - public Vfs.Dir createDir(final URL url) {return new HttpDir(url);} - }); - - testVfsDir(new URL("http://mirrors.ibiblio.org/pub/mirrors/maven2/org/slf4j/slf4j-api/1.5.6/slf4j-api-1.5.6.jar")); - } - - //this is just for the test... - static class HttpDir implements Vfs.Dir { - private final File file; - private final ZipDir zipDir; - private final String path; - - HttpDir(URL url) { - this.path = url.toExternalForm(); - try {file = downloadTempLocally(url);} - catch (IOException e) {throw new RuntimeException(e);} - try { zipDir = new ZipDir(new JarFile(file)); } catch (Exception e) { throw new RuntimeException(e); } - } - - public String getPath() {return path;} - public Iterable getFiles() {return zipDir.getFiles();} - public void close() {file.delete();} - - private static java.io.File downloadTempLocally(URL url) throws IOException { - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - if (connection.getResponseCode() == 200) { - java.io.File temp = java.io.File.createTempFile("urlToVfs", "tmp"); - FileOutputStream out = new FileOutputStream(temp); - DataInputStream in = new DataInputStream(connection.getInputStream()); - - int len; byte ch[] = new byte[1024]; - while ((len = in.read(ch)) != -1) {out.write(ch, 0, len);} - - connection.disconnect(); - return temp; - } - - return null; - } - } - - @Test - public void vfsFromJarWithInnerJars() { - //todo? - } - @Test - public void jarInputStream() { - JavassistAdapter javassistAdapter = new JavassistAdapter(); - - for (URL jar : ClasspathHelper.forClassLoader()) { - try { - for (Vfs.File file : Iterables.limit(new JarInputDir(jar).getFiles(), 5)) { - if (file.getName().endsWith(".class")) { - String className = javassistAdapter.getClassName(javassistAdapter.getOrCreateClassObject(file)); - } - } - } catch (Exception e) { - throw new RuntimeException(e); + private void testVfsDir(Vfs.Dir dir) { + JavassistAdapter mdAdapter = new JavassistAdapter(); + Vfs.File file = null; + for (Vfs.File f : dir.getFiles()) { + if (f.getRelativePath().endsWith(".class")) { + file = f; + break; } } - } - - // - private URL getSomeJar() { - Collection urls = ClasspathHelper.forClassLoader(); - for (URL url : urls) { - if (!url.toExternalForm().contains("surefire") && url.toExternalForm().endsWith(".jar")) return url; //damn - } - throw new RuntimeException(); - } - private URL getSomeDirectory() { - try { - return new File(ReflectionsTest.getUserDir()).toURI().toURL(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } + ClassFile stringCF = mdAdapter.getOrCreateClassObject(file); + String className = mdAdapter.getClassName(stringCF); + assertFalse(className.isEmpty()); } } \ No newline at end of file From 1f6c84f034a6987b609f449353c820df416979f6 Mon Sep 17 00:00:00 2001 From: ronma Date: Mon, 6 Jan 2020 09:51:30 +0700 Subject: [PATCH 2/4] migrate to java 8. removed guava and migrated to streams api. simplified store. cleanups. --- .travis.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 521e981d..66f2c69e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,8 +5,3 @@ jdk: - oraclejdk11 - openjdk8 - openjdk11 - -addons: - apt: - packages: - - oracle-java8-installer \ No newline at end of file From 83433db40b769600caa52d0ed6cf067ad6581079 Mon Sep 17 00:00:00 2001 From: ronma Date: Tue, 7 Jan 2020 20:22:04 +0700 Subject: [PATCH 3/4] migrate to java 8. removed guava and migrated to streams api. simplified store. cleanups. --- .travis.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 66f2c69e..3ac47107 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,5 @@ language: java jdk: - - oraclejdk8 - - oraclejdk11 - openjdk8 - openjdk11 From 7befa02aa55b038b492087438dc61199227592ab Mon Sep 17 00:00:00 2001 From: ronma Date: Tue, 7 Jan 2020 23:25:04 +0700 Subject: [PATCH 4/4] migrate to java 8. removed guava and migrated to streams api. simplified store. cleanups. --- .../java/org/reflections/ReflectionUtils.java | 45 ++++++---------- .../java/org/reflections/Reflections.java | 52 ++++++++----------- src/main/java/org/reflections/Store.java | 31 ++++------- .../adapters/JavaReflectionAdapter.java | 23 ++------ .../adapters/JavassistAdapter.java | 39 ++++++-------- src/main/java/org/reflections/util/Utils.java | 41 ++++----------- .../java/org/reflections/vfs/JarInputDir.java | 2 +- src/main/java/org/reflections/vfs/Vfs.java | 6 +-- 8 files changed, 81 insertions(+), 158 deletions(-) diff --git a/src/main/java/org/reflections/ReflectionUtils.java b/src/main/java/org/reflections/ReflectionUtils.java index aa178136..bd82e2ca 100644 --- a/src/main/java/org/reflections/ReflectionUtils.java +++ b/src/main/java/org/reflections/ReflectionUtils.java @@ -11,13 +11,15 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.reflections.util.Utils.filter; @@ -194,9 +196,8 @@ public static Predicate withAnnotations(final An if (input != null) { Annotation[] inputAnnotations = input.getAnnotations(); if (inputAnnotations.length == annotations.length) { - for (int i = 0; i < inputAnnotations.length; i++) { - if (!areAnnotationMembersMatching(inputAnnotations[i], annotations[i])) return false; - } + return IntStream.range(0, inputAnnotations.length) + .allMatch(i -> areAnnotationMembersMatching(inputAnnotations[i], annotations[i])); } } return true; @@ -325,14 +326,10 @@ public static Class forName(String typeName, ClassLoader... classLoaders) { /** try to resolve all given string representation of types to a list of java types */ public static Set> forNames(final Collection classes, ClassLoader... classLoaders) { - Set> result = new LinkedHashSet<>(); - for (String className : classes) { - Class type = forName(className, classLoaders); - if (type != null) { - result.add((Class) type); - } - } - return result; + return classes.stream() + .map(className -> (Class) forName(className, classLoaders)) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); } private static Class[] parameterTypes(Member member) { @@ -342,24 +339,18 @@ private static Class[] parameterTypes(Member member) { } private static Set parameterAnnotations(Member member) { - Set result = new HashSet<>(); Annotation[][] annotations = member instanceof Method ? ((Method) member).getParameterAnnotations() : member instanceof Constructor ? ((Constructor) member).getParameterAnnotations() : null; - for (Annotation[] annotation : annotations) Collections.addAll(result, annotation); - return result; + return Arrays.stream(annotations).flatMap(Arrays::stream).collect(Collectors.toSet()); } - private static Set> annotationTypes(Iterable annotations) { - Set> result = new HashSet<>(); - for (Annotation annotation : annotations) result.add(annotation.annotationType()); - return result; + private static Set> annotationTypes(Collection annotations) { + return annotations.stream().map(Annotation::annotationType).collect(Collectors.toSet()); } private static Class[] annotationTypes(Annotation[] annotations) { - Class[] result = new Class[annotations.length]; - for (int i = 0; i < annotations.length; i++) result[i] = annotations[i].annotationType(); - return result; + return Arrays.stream(annotations).map(Annotation::annotationType).toArray(Class[]::new); } // @@ -402,12 +393,8 @@ private static boolean isAssignable(Class[] childClasses, Class[] parentClasses) if (childClasses.length != parentClasses.length) { return false; } - for (int i = 0; i < childClasses.length; i++) { - if (!parentClasses[i].isAssignableFrom(childClasses[i]) || - (parentClasses[i] == Object.class && childClasses[i] != Object.class)) { - return false; - } - } - return true; + return IntStream.range(0, childClasses.length) + .noneMatch(i -> !parentClasses[i].isAssignableFrom(childClasses[i]) || + parentClasses[i] == Object.class && childClasses[i] != Object.class); } } diff --git a/src/main/java/org/reflections/Reflections.java b/src/main/java/org/reflections/Reflections.java index 627f6a6f..724b67e6 100644 --- a/src/main/java/org/reflections/Reflections.java +++ b/src/main/java/org/reflections/Reflections.java @@ -401,8 +401,7 @@ private void expandSupertypes(Store store, String key, Class type) { *

depends on SubTypesScanner configured */ public Set> getSubTypesOf(final Class type) { - return ReflectionUtils.forNames( - store.getAll(SubTypesScanner.class, Collections.singletonList(type.getName())), loaders()); + return forNames(store.getAll(SubTypesScanner.class, type.getName()), loaders()); } /** @@ -428,8 +427,8 @@ public Set> getTypesAnnotatedWith(final Class ann */ public Set> getTypesAnnotatedWith(final Class annotation, boolean honorInherited) { Set annotated = store.get(TypeAnnotationsScanner.class, annotation.getName()); - Set classes = getAllAnnotated(annotated, annotation.isAnnotationPresent(Inherited.class), honorInherited); - return new HashSet<>(concat(forNames(annotated, loaders()), forNames(classes, loaders()))); + annotated.addAll(getAllAnnotated(annotated, annotation, honorInherited)); + return forNames(annotated, loaders()); } /** @@ -448,25 +447,26 @@ public Set> getTypesAnnotatedWith(final Annotation annotation) { */ public Set> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited) { Set annotated = store.get(TypeAnnotationsScanner.class, annotation.annotationType().getName()); - Set> filter = filter(forNames(annotated, loaders()), withAnnotation(annotation)); - Set classes = getAllAnnotated(new HashSet<>(names(filter)), annotation.annotationType().isAnnotationPresent(Inherited.class), honorInherited); - return concat(filter, forNames(filter(classes, s -> !annotated.contains(s)), loaders())); + Set> allAnnotated = filter(forNames(annotated, loaders()), withAnnotation(annotation)); + Set> classes = forNames(filter(getAllAnnotated(names(allAnnotated), annotation.annotationType(), honorInherited), s -> !annotated.contains(s)), loaders()); + allAnnotated.addAll(classes); + return allAnnotated; } - protected Set getAllAnnotated(Set annotated, boolean inherited, boolean honorInherited) { + protected Collection getAllAnnotated(Collection annotated, Class annotation, boolean honorInherited) { if (honorInherited) { - if (inherited) { - Set subTypes = store.get(SubTypesScanner.class, filter(annotated, (Predicate) input -> { + if (annotation.isAnnotationPresent(Inherited.class)) { + Set subTypes = store.get(SubTypesScanner.class, filter(annotated, input -> { final Class type = forName(input, loaders()); return type != null && !type.isInterface(); })); - return concat(subTypes, store.getAll(SubTypesScanner.class, subTypes)); + return store.getAllIncluding(SubTypesScanner.class, subTypes); } else { return annotated; } } else { - Set subTypes = concat(annotated, store.getAll(TypeAnnotationsScanner.class, annotated)); - return concat(subTypes, store.getAll(SubTypesScanner.class, subTypes)); + Collection subTypes = store.getAllIncluding(TypeAnnotationsScanner.class, annotated); + return store.getAllIncluding(SubTypesScanner.class, subTypes); } } @@ -475,8 +475,7 @@ protected Set getAllAnnotated(Set annotated, boolean inherited, *

depends on MethodAnnotationsScanner configured */ public Set getMethodsAnnotatedWith(final Class annotation) { - Set methods = store.get(MethodAnnotationsScanner.class, annotation.getName()); - return getMethodsFromDescriptors(methods, loaders()); + return getMethodsFromDescriptors(store.get(MethodAnnotationsScanner.class, annotation.getName()), loaders()); } /** @@ -505,10 +504,7 @@ public Set getMethodsWithAnyParamAnnotated(Class a /** get methods with any parameter annotated with given annotation, including annotation member values matching */ public Set getMethodsWithAnyParamAnnotated(Annotation annotation) { - return getMethodsWithAnyParamAnnotated(annotation.annotationType()) - .stream() - .filter(withAnyParameterAnnotation(annotation)) - .collect(Collectors.toSet()); + return filter(getMethodsWithAnyParamAnnotated(annotation.annotationType()), withAnyParameterAnnotation(annotation)); } /** @@ -516,8 +512,7 @@ public Set getMethodsWithAnyParamAnnotated(Annotation annotation) { *

depends on MethodAnnotationsScanner configured */ public Set getConstructorsAnnotatedWith(final Class annotation) { - Set methods = store.get(MethodAnnotationsScanner.class, annotation.getName()); - return getConstructorsFromDescriptors(methods, loaders()); + return getConstructorsFromDescriptors(store.get(MethodAnnotationsScanner.class, annotation.getName()), loaders()); } /** @@ -540,10 +535,7 @@ public Set getConstructorsWithAnyParamAnnotated(Class getConstructorsWithAnyParamAnnotated(Annotation annotation) { - return getConstructorsWithAnyParamAnnotated(annotation.annotationType()) - .stream() - .filter(withAnyParameterAnnotation(annotation)) - .collect(Collectors.toSet()); + return filter(getConstructorsWithAnyParamAnnotated(annotation.annotationType()), withAnyParameterAnnotation(annotation)); } /** @@ -551,11 +543,9 @@ public Set getConstructorsWithAnyParamAnnotated(Annotation annotati *

depends on FieldAnnotationsScanner configured */ public Set getFieldsAnnotatedWith(final Class annotation) { - final Set result = new HashSet<>(); - for (String annotated : store.get(FieldAnnotationsScanner.class, annotation.getName())) { - result.add(getFieldFromString(annotated, loaders())); - } - return result; + return store.get(FieldAnnotationsScanner.class, annotation.getName()).stream() + .map(annotated -> getFieldFromString(annotated, loaders())) + .collect(Collectors.toSet()); } /** @@ -661,7 +651,7 @@ public File save(final String filename) { */ public File save(final String filename, final Serializer serializer) { File file = serializer.save(this, filename); - if (log != null) //noinspection ConstantConditions + if (log != null) log.info("Reflections successfully saved in " + file.getAbsolutePath() + " using " + serializer.getClass().getSimpleName()); return file; } diff --git a/src/main/java/org/reflections/Store.java b/src/main/java/org/reflections/Store.java index 008baf0b..4e4ecf6c 100644 --- a/src/main/java/org/reflections/Store.java +++ b/src/main/java/org/reflections/Store.java @@ -42,22 +42,22 @@ private Map> get(String index) { } /** get the values stored for the given {@code index} and {@code keys} */ - public Set get(Class scannerClass, String keys) { - return get(index(scannerClass), keys); + public Set get(Class scannerClass, String key) { + return get(index(scannerClass), Collections.singletonList(key)); } /** get the values stored for the given {@code index} and {@code keys} */ - public Set get(String index, String keys) { - return get(index, Collections.singletonList(keys)); + public Set get(String index, String key) { + return get(index, Collections.singletonList(key)); } /** get the values stored for the given {@code index} and {@code keys} */ - public Set get(Class scannerClass, Iterable keys) { + public Set get(Class scannerClass, Collection keys) { return get(index(scannerClass), keys); } /** get the values stored for the given {@code index} and {@code keys} */ - public Set get(String index, Iterable keys) { + private Set get(String index, Collection keys) { Map> mmap = get(index); Set result = new LinkedHashSet<>(); for (String key : keys) { @@ -70,7 +70,8 @@ public Set get(String index, Iterable keys) { } /** recursively get the values stored for the given {@code index} and {@code keys}, including keys */ - private Set getAllIncluding(String index, Set keys) { + public Set getAllIncluding(Class scannerClass, Collection keys) { + String index = index(scannerClass); Map> mmap = get(index); List workKeys = new ArrayList<>(keys); @@ -89,22 +90,12 @@ private Set getAllIncluding(String index, Set keys) { /** recursively get the values stored for the given {@code index} and {@code keys}, not including keys */ public Set getAll(Class scannerClass, String key) { - return getAll(index(scannerClass), key); - } - - /** recursively get the values stored for the given {@code index} and {@code keys}, not including keys */ - public Set getAll(String index, String key) { - return getAllIncluding(index, get(index, key)); - } - - /** recursively get the values stored for the given {@code index} and {@code keys}, not including keys */ - public Set getAll(Class scannerClass, Iterable keys) { - return getAll(index(scannerClass), keys); + return getAllIncluding(scannerClass, get(scannerClass, key)); } /** recursively get the values stored for the given {@code index} and {@code keys}, not including keys */ - public Set getAll(String index, Iterable keys) { - return getAllIncluding(index, get(index, keys)); + public Set getAll(Class scannerClass, Collection keys) { + return getAllIncluding(scannerClass, get(scannerClass, keys)); } public Set keys(String index) { diff --git a/src/main/java/org/reflections/adapters/JavaReflectionAdapter.java b/src/main/java/org/reflections/adapters/JavaReflectionAdapter.java index 9c854c24..aab18adf 100644 --- a/src/main/java/org/reflections/adapters/JavaReflectionAdapter.java +++ b/src/main/java/org/reflections/adapters/JavaReflectionAdapter.java @@ -11,7 +11,9 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; import static org.reflections.ReflectionUtils.forName; import static org.reflections.util.Utils.join; @@ -36,19 +38,10 @@ public String getMethodName(Member method) { } public List getParameterNames(final Member member) { - List result = new ArrayList<>(); - Class[] parameterTypes = member instanceof Method ? ((Method) member).getParameterTypes() : member instanceof Constructor ? ((Constructor) member).getParameterTypes() : null; - if (parameterTypes != null) { - for (Class paramType : parameterTypes) { - String name = getName(paramType); - result.add(name); - } - } - - return result; + return parameterTypes != null ? Arrays.stream(parameterTypes).map(JavaReflectionAdapter::getName).collect(Collectors.toList()) : Collections.emptyList(); } public List getClassAnnotationNames(Class aClass) { @@ -122,9 +115,7 @@ public String getSuperclassName(Class cls) { public List getInterfacesNames(Class cls) { Class[] classes = cls.getInterfaces(); - List names = new ArrayList<>(classes != null ? classes.length : 0); - if (classes != null) for (Class cls1 : classes) names.add(cls1.getName()); - return names; + return classes != null ? Arrays.stream(classes).map(Class::getName).collect(Collectors.toList()) : Collections.emptyList(); } public boolean acceptsInput(String file) { @@ -133,11 +124,7 @@ public boolean acceptsInput(String file) { // private List getAnnotationNames(Annotation[] annotations) { - List names = new ArrayList<>(annotations.length); - for (Annotation annotation : annotations) { - names.add(annotation.annotationType().getName()); - } - return names; + return Arrays.stream(annotations).map(annotation -> annotation.annotationType().getName()).collect(Collectors.toList()); } public static String getName(Class type) { diff --git a/src/main/java/org/reflections/adapters/JavassistAdapter.java b/src/main/java/org/reflections/adapters/JavassistAdapter.java index 7a3c286b..dc5cd93c 100644 --- a/src/main/java/org/reflections/adapters/JavassistAdapter.java +++ b/src/main/java/org/reflections/adapters/JavassistAdapter.java @@ -18,7 +18,11 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static javassist.bytecode.AccessFlag.isPrivate; import static javassist.bytecode.AccessFlag.isProtected; @@ -33,12 +37,10 @@ public class JavassistAdapter implements MetadataAdapter getFields(final ClassFile cls) { - //noinspection unchecked return cls.getFields(); } public List getMethods(final ClassFile cls) { - //noinspection unchecked return cls.getMethods(); } @@ -153,29 +155,19 @@ public boolean acceptsInput(String file) { // private List getAnnotationNames(final AnnotationsAttribute... annotationsAttributes) { - List result = new ArrayList<>(); - if (annotationsAttributes != null) { - for (AnnotationsAttribute annotationsAttribute : annotationsAttributes) { - if (annotationsAttribute != null) { - for (Annotation annotation : annotationsAttribute.getAnnotations()) { - result.add(annotation.getTypeName()); - } - } - } + return Arrays.stream(annotationsAttributes) + .filter(Objects::nonNull) + .flatMap(annotationsAttribute -> Arrays.stream(annotationsAttribute.getAnnotations())) + .map(Annotation::getTypeName) + .collect(Collectors.toList()); + } else { + return Collections.emptyList(); } - - return result; } private List getAnnotationNames(final Annotation[] annotations) { - List result = new ArrayList<>(); - - for (Annotation annotation : annotations) { - result.add(annotation.getTypeName()); - } - - return result; + return Arrays.stream(annotations).map(Annotation::getTypeName).collect(Collectors.toList()); } private List splitDescriptorToTypeNames(final String descriptors) { @@ -190,10 +182,9 @@ private List splitDescriptorToTypeNames(final String descriptors) { } indices.add(descriptors.length()); - for (int i = 0; i < indices.size() - 1; i++) { - String s1 = Descriptor.toString(descriptors.substring(indices.get(i), indices.get(i + 1))); - result.add(s1); - } + result = IntStream.range(0, indices.size() - 1) + .mapToObj(i -> Descriptor.toString(descriptors.substring(indices.get(i), indices.get(i + 1)))) + .collect(Collectors.toList()); } diff --git a/src/main/java/org/reflections/util/Utils.java b/src/main/java/org/reflections/util/Utils.java index 3dbab487..b9402635 100644 --- a/src/main/java/org/reflections/util/Utils.java +++ b/src/main/java/org/reflections/util/Utils.java @@ -12,7 +12,6 @@ import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; @@ -20,8 +19,7 @@ import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; +import java.util.stream.IntStream; import static org.reflections.ReflectionUtils.forName; @@ -31,13 +29,7 @@ public abstract class Utils { public static String repeat(String string, int times) { - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < times; i++) { - sb.append(string); - } - - return sb.toString(); + return IntStream.range(0, times).mapToObj(i -> string).collect(Collectors.joining()); } /** @@ -47,10 +39,6 @@ public static boolean isEmpty(String s) { return s == null || s.length() == 0; } - public static boolean isEmpty(Object[] objects) { - return objects == null || objects.length == 0; - } - public static File prepareFile(String filename) { File file = new File(filename); File parent = file.getAbsoluteFile().getParentFile(); @@ -73,11 +61,7 @@ public static Member getMemberFromDescriptor(String descriptor, ClassLoader... c Class[] parameterTypes = null; if (!isEmpty(methodParameters)) { String[] parameterNames = methodParameters.split(","); - List> result = new ArrayList<>(parameterNames.length); - for (String name : parameterNames) { - result.add(forName(name.trim(), classLoaders)); - } - parameterTypes = result.toArray(new Class[result.size()]); + parameterTypes = Arrays.stream(parameterNames).map(name -> forName(name.trim(), classLoaders)).toArray(Class[]::new); } Class aClass = forName(className, classLoaders); @@ -182,10 +166,8 @@ public static String name(Class type) { } - public static List names(Iterable> types) { - List result = new ArrayList<>(); - for (Class type : types) result.add(name(type)); - return result; + public static List names(Collection> types) { + return types.stream().map(Utils::name).collect(Collectors.toList()); } public static List names(Class... types) { @@ -210,23 +192,18 @@ public static Predicate and(Predicate... predicates) { return Arrays.stream(predicates).reduce(t -> true, Predicate::and); } - public static Stream stream(Iterable elements) { - return StreamSupport.stream(elements.spliterator(), false); - } - public static String join(Collection elements, String delimiter) { return elements.stream().map(Object::toString).collect(Collectors.joining(delimiter)); } - public static Set concat(Set forNames, Set forNames1) { - forNames.addAll(forNames1); - return forNames; - } - public static Set filter(Collection result, Predicate... predicates) { return result.stream().filter(and(predicates)).collect(Collectors.toSet()); } + public static Set filter(Collection result, Predicate predicate) { + return result.stream().filter(predicate).collect(Collectors.toSet()); + } + public static Set filter(T[] result, Predicate... predicates) { return Arrays.stream(result).filter(and(predicates)).collect(Collectors.toSet()); } diff --git a/src/main/java/org/reflections/vfs/JarInputDir.java b/src/main/java/org/reflections/vfs/JarInputDir.java index aebf9184..01917287 100644 --- a/src/main/java/org/reflections/vfs/JarInputDir.java +++ b/src/main/java/org/reflections/vfs/JarInputDir.java @@ -27,7 +27,7 @@ public String getPath() { } public Iterable getFiles() { - return (Iterable) () -> new Iterator() { + return () -> new Iterator() { { try { jarInputStream = new JarInputStream(url.openConnection().getInputStream()); } diff --git a/src/main/java/org/reflections/vfs/Vfs.java b/src/main/java/org/reflections/vfs/Vfs.java index 4c49edf6..ad4d93b3 100644 --- a/src/main/java/org/reflections/vfs/Vfs.java +++ b/src/main/java/org/reflections/vfs/Vfs.java @@ -161,7 +161,7 @@ public static java.io.File getFile(URL url) { try { path = url.toURI().getSchemeSpecificPart(); if ((file = new java.io.File(path)).exists()) return file; - } catch (URISyntaxException e) { + } catch (URISyntaxException ignored) { } try { @@ -169,7 +169,7 @@ public static java.io.File getFile(URL url) { if (path.contains(".jar!")) path = path.substring(0, path.lastIndexOf(".jar!") + ".jar".length()); if ((file = new java.io.File(path)).exists()) return file; - } catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException ignored) { } try { @@ -184,7 +184,7 @@ public static java.io.File getFile(URL url) { path = path.replace("%20", " "); if ((file = new java.io.File(path)).exists()) return file; - } catch (Exception e) { + } catch (Exception ignored) { } return null;