add ReflexionUtil.getAllSubclasses(Class) with 10 minutes cache (because it takes time to compute the result)

This commit is contained in:
Marc Baloup 2020-11-07 15:00:47 +01:00
parent ea39a7a84a
commit a73f428bc4
Signed by: marcbal
GPG Key ID: BBC0FE3ABC30B893
2 changed files with 62 additions and 0 deletions

32
pom.xml
View File

@ -33,5 +33,37 @@
<version>1.2</version> <version>1.2</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
<version>4.8.90</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>io.github.classgraph:classgraph</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>

View File

@ -2,6 +2,15 @@ package fr.pandacube.util;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;
public class ReflexionUtil { public class ReflexionUtil {
@ -150,6 +159,27 @@ public class ReflexionUtil {
private static Cache<Class<?>, List<Class<?>>> subClassesLists = CacheBuilder.newBuilder()
.expireAfterAccess(10, TimeUnit.MINUTES)
.build();
public static <E> List<Class<? extends E>> getAllSubclasses(Class<E> clazz) {
try {
@SuppressWarnings("unchecked")
List<Class<? extends E>> classes = (List<Class<? extends E>>) (List<?>) subClassesLists.get(clazz, () -> {
try (ScanResult scanResult = new ClassGraph().enableClassInfo().ignoreClassVisibility().scan()) {
return scanResult.getSubclasses(clazz.getName()).loadClasses();
}
});
return classes;
} catch(ExecutionException e) {
Log.severe(e);
return null;
}
}
} }