First off, I want to say that I read this StackOverflow post
My current understanding is that if you want to get all classes from a package without writing a ton of code lines, you are basically stuck with the Reflections
API. Here are some of the options:
Option 1.
private static Set<Class<?>> getClassesFromPackage(String packageName) {
Reflections reflections = new Reflections(packageName, new SubTypesScanner(false));
return new HashSet<>(reflections.getSubTypesOf(Object.class));
}
Not optimal: SubTypesScanner
is deprecated so you'll get a warning
Option 2.
private static Set<Class<?>> getClassesFromPackage(String packageName) {
Reflections reflections = new Reflections(packageName, Scanners.SubTypes.filterResultsBy(s -> true));
return new HashSet<>(reflections.getSubTypesOf(Object.class));
}
Not optimal: Scanners.SubTypes.filterResultsBy(s -> true)
is clumsy AF so you either get code that is not easily readable or you have to provide some meta commentary
private static Set<Class<?>> getClassesFromPackage(String packageName) {
Reflections reflections = new Reflections(packageName, getStuffThatMakesItWork());
return new HashSet<>(reflections.getSubTypesOf(Object.class));
}
private static Scanners getStuffThatMakesItWork() {
return Scanners.SubTypes.filterResultsBy(s -> true);
}
Wouldn't it be peachy if I could write just this
private static Set<Class<?>> getClassesFromPackage(String packageName) {
Reflections reflections = new Reflections(packageName);
return new HashSet<>(reflections.getSubTypesOf(Object.class));
}
It is so much more readable, but sadly it doesn't work (the returned set would contain zero items)
What is the best way to scan for package classes?
Criteria:
- The code should be as short as possible.
- The code should be readable (a random person shouldn't get any WTF moments when looking at it)
- You shouldn't get warnings
One thing I haven't mentioned yet is that the whole Reflections
library is not maintained since 2021 so it may not be a solid long-term solution to rely on it. Are there alternatives that are at least just as good?
Aucun commentaire:
Enregistrer un commentaire